协议缓冲区中的字典
有没有办法使用协议缓冲区序列化字典,或者如果需要的话我必须使用 Thrift?
Is there any way to serialize a dictionary using protocol buffers, or I'll have to use Thrift if I need that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于未来的答案寻求者,ProtoBuf 现在原生支持地图:
For future answer seekers, ProtoBuf now supports Maps natively:
Protobuf 规范现在原生支持字典(地图)。
原始答案
人们通常将字典写成键值对列表,然后在另一端重建字典。
Protobuf specification now supports dictionaries (maps) natively.
Original answer
People typically write down the dictionary as a list of key-value pairs, and then rebuild the dictionary on the other end.
您可以检查 ProtoText 包。
假设您要将字典
person_dict
序列化为personbuf_pb2
模块中定义的预定义PersonBuf
protobuf 对象。在这种情况下,要使用 ProtoText,
You can check the ProtoText package.
Assume you want to serialize a dict
person_dict
to a pre-definedPersonBuf
protobuf object defined inpersonbuf_pb2
module.In this case, to use ProtoText,
我首先评论@Flassari的答案,因为它真的很方便。
但是,就我而言,我需要
map
其中:这里我只想返回一个字典,对于每种类型,该字典包含 AnyModel 列表
但是,我没有找到比 @JesperE 提出的更好的解决方法,因此我执行了以下操作: (as you can不使用枚举作为映射中的键)
这里我使用我从服务器/客户端选择的代码语言将枚举转换为字符串
所以这两种方法实际上都是有效的答案IMO,取决于您的要求。
I firstly comment the @Flassari 's answer as it is really convenient.
However, in my case, I needed
map<Type, repeated AnyModel>
where :Here I just want to return a dictionary that, for each type, contain a list of AnyModel
However, I didn't find a better workaround than the one proposed by @JesperE so I did the following: (as you can't use enum as key in map)
Here I convert from/to string my enum using my chosen code languages from both server/client side
So both approaches are actually valid answers IMO, depends on your requirements.