protocol-buffers - Protobuf3 : How to describe map of repeated string?

标签 protocol-buffers protocol-buffers-3

Official documentation about map type说:

map<key_type, value_type> map_field = N;

...where the key_type can be any integral or string type (so, any scalar type except for floating point types and bytes). The value_type can be any type.

我想定义一个 map<string, repeated string>字段,但在我的 libprotoc 3.0.0 上似乎是非法的,提示Expected ">" .所以想知道有没有什么办法可以把重复的字符串放到map中。

可能的解决方法是:

message ListOfString {
    repeated string value = 1;
}

// Then define:
map<string, ListOfString> mapToRepeatedString = 1;

但是ListOfString这里看起来多余。

最佳答案

我有同样的需求,得到了同样的错误。我不相信这是可能的。这是语言规范中的相关 BNF 定义。

https://developers.google.com/protocol-buffers/docs/reference/proto3-spec

messageType = [ "." ] { ident "." } messageName
mapField = "map" "<" keyType "," type ">" mapName "=" fieldNumber [ "["fieldOptions "]" ] ";"
type = "double" | "float" | "int32" | "int64" | "uint32" | "uint64"
  | "sint32" | "sint64" | "fixed32" | "fixed64" | "sfixed32" | "sfixed64"
  | "bool" | "string" | "bytes" | messageType | enumType
messageName = ident
ident = letter { letter | decimalDigit | "_" }
field = [ "repeated" ] type fieldName "=" fieldNumber [ "[" fieldOptions "]" ] ";"

“重复”关键字只出现在字段定义中。 map 定义需要一个“类型”,其中不包括重复关键字。

这意味着有几个选项。

  • > 您可以按照您的指示围绕重复值创建一个包装器。
  • 有一种人们定义 map 的旧方法,这种方法比较繁琐但等效。这是语言指南中的向后兼容示例。 https://developers.google.com/protocol-buffers/docs/proto3#maps
        message MapFieldEntry {
          key_type key = 1;
          repeated value_type value = 2;
        }
        repeated MapFieldEntry map_field = N;
        
    您需要自己将数据转换为 map ,但这在大多数语言中应该是微不足道的。在 java 中:
        List<MapFieldEntry> map_field = // Existing list from protobuf.
        Map<key_type, List<value_type>> = map_field.stream()
            .collect(Collectors.toMap(kv -> kv.key, kv -> kv.value));
    
        
  • > 使用 google.protobuf.ListValue https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#listvalue 这是来自其众所周知类型的无类型列表集合。

关于protocol-buffers - Protobuf3 : How to describe map of repeated string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495860/

相关文章:

python - Protobuf3 : Serialize a Python object to JSON

python - 如何在 python Beam 中制作通用的 Protobuf 解析器 DoFn?

Android NDK 未定义对 google protobuf 的引用

java - 带反射的嵌套 Protocol Buffer

java - Protocol Buffer ,序列化数据中有什么?

android-studio - 在单元测试中处理 protobuf 类时出现 NoSuchMethod 错误

java - 如何在 Google Protobufs 中完整读取带有分隔消息的文件?

c# - 在 c# visual studio 中编译 Protocol Buffer 3 时间戳类型?

java - protoc 自定义插件出错并显示程序未找到或不可执行