java 您将如何使用协议缓冲区对 Map<String, Object> 进行编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1102900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would you encode a Map<String, Object> using Protocol Buffers?
提问by arturh
I'm trying to use Protocol Buffersfor message serialization.
我正在尝试使用协议缓冲区进行消息序列化。
My message format should contain Map< String, Object > entries ... but how do I write the .proto definition?
我的消息格式应该包含 Map< String, Object > 条目......但我如何编写 .proto 定义?
As far as I know, Protocol Buffers does not have a build-in Map type. I could model around that using repeating fields. But the big problem I have is, that you need to define all your types. I want my message to be flexible, so I can't specify the types.
据我所知,Protocol Buffers 没有内置 Map 类型。我可以使用重复字段围绕它建模。但我遇到的大问题是,您需要定义所有类型。我希望我的消息灵活,所以我不能指定类型。
Any ideas?
有任何想法吗?
采纳答案by Jon Skeet
I'd model a tuple with a key and a value (probably one value field per type that the value could be). Then just have a repeated list of that tuple type. You'd need to build the map itself in code.
我会用一个键和一个值来建模一个元组(可能是每个类型的值可能是一个值字段)。然后只需重复该元组类型的列表。您需要在代码中构建地图本身。
When you say you can't specify the types - what sort of types are you talking about? If you have an optional field of each type in the tuple, then that would cope for all the primitives - and you couldmap messages by serializing them into a byte string.
当你说你不能指定类型时 - 你在说什么类型?如果元组中有每种类型的可选字段,那么这将适用于所有原语 - 您可以通过将消息序列化为字节字符串来映射消息。
It sounds like the level of "unstructure" you have may not be a good fit for PB though.
听起来您所拥有的“非结构化”级别可能不太适合 PB。

