Protobuf 字典列表
Protobuf list of dictionaries
我正在尝试在我的 .proto 中定义一个字典列表
我找到的所有示例都提供了带有单个键值对的字典:
message Pair {
string key = 1;
string value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
或类似的东西:
message Dictionary {
message Pair {
map<string, string> values = 1;
}
repeated Pair pairs = 1;
}
但是我如何处理更大的混合类型字典?
{
'k1': 1,
'k2': 2,
'k3': 'three',
'k4': [1,2,3]
}
更复杂的是,一旦我定义了混合值字典,我需要创建一条消息,它是这些字典的列表。我认为这就像使用嵌套的字典创建另一个重复消息一样简单:
message DictList {
repeated Dictionary dlist = 1;
}
我想到的几个点子:
- 似乎应该可以(如果您预先知道所有值类型)使用
oneof
作为值 (https://developers.google.com/protocol-buffers/docs/proto3#oneof)。这可以解决问题,例如
message Value {
oneof oneof_values {
string svalue = 1;
int ivalue = 2;
...
}
}
message Pair {
string key = 1;
Value value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
但是您不能在 oneof
中使用 map
或 repeated
。
您可以使用可选字段并将它们全部定义为消息定义中的值。然后只设置那些你实际使用的。
您可以使用包装器或已知类型,例如Value
: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value
编辑
对于Value
,可以这样使用:
map<string, google.protobuf.Value> dict = 1;
- 使用
struct
(由for_stack建议),可以在这里看到:
我正在尝试在我的 .proto 中定义一个字典列表
我找到的所有示例都提供了带有单个键值对的字典:
message Pair {
string key = 1;
string value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
或类似的东西:
message Dictionary {
message Pair {
map<string, string> values = 1;
}
repeated Pair pairs = 1;
}
但是我如何处理更大的混合类型字典?
{
'k1': 1,
'k2': 2,
'k3': 'three',
'k4': [1,2,3]
}
更复杂的是,一旦我定义了混合值字典,我需要创建一条消息,它是这些字典的列表。我认为这就像使用嵌套的字典创建另一个重复消息一样简单:
message DictList {
repeated Dictionary dlist = 1;
}
我想到的几个点子:
- 似乎应该可以(如果您预先知道所有值类型)使用
oneof
作为值 (https://developers.google.com/protocol-buffers/docs/proto3#oneof)。这可以解决问题,例如
message Value {
oneof oneof_values {
string svalue = 1;
int ivalue = 2;
...
}
}
message Pair {
string key = 1;
Value value = 2;
}
message Dictionary {
repeated Pair pairs = 1;
}
但是您不能在 oneof
中使用 map
或 repeated
。
您可以使用可选字段并将它们全部定义为消息定义中的值。然后只设置那些你实际使用的。
您可以使用包装器或已知类型,例如
Value
: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value
编辑
对于Value
,可以这样使用:
map<string, google.protobuf.Value> dict = 1;
- 使用
struct
(由for_stack建议),可以在这里看到: