首页 > 解决方案 > 将对象数组表示为 protobuf 消息

问题描述

我想创建一个表示对象数组的 protobuf 消息。

例子

[
  {
    "firstKey": "firstValue",
    "secondKey": "secondValue",
  },
  {
    "firstKey": "firstValue",
    "secondKey": "secondValue",
  },
  ...
]

伪代码(不是有效的语法)

syntax = "proto3";

message Entry {
  string firstKey = 1;
  string secondKey = 2;
}

repeated message Response {
  ...Entry;
}

我找不到办法做到这一点。甚至有可能还是我被迫像这样嵌套它?

syntax = "proto3";

message Entry {
  string firstKey = 1;
  string secondKey = 2;
}

message Response {
  repeated Entry data = 2;
}

标签: jsonprotocol-buffers

解决方案


repeated is only permitted on message fields (use of type) not (definition of) types:

https://developers.google.com/protocol-buffers/docs/overview#specifying_field_rules

This makes sense as your alternative would require that the type is always repeated which is less useful; if you have "many of" you're likely to want to use "one of" too.

You can nest the definition so that it is only applicable to the referencing type:

https://developers.google.com/protocol-buffers/docs/overview#nested


推荐阅读