Dictionary in protocol buffers
Is there any way to serialize a diction开发者_JAVA技巧ary using protocol buffers, or I'll have to use Thrift if I need that?
For future answer seekers, ProtoBuf now supports Maps natively:
message MapMessage
{
    map<string, string> MyMap = 1;
}
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.
message Pair {
   string key = 1;
   string value = 2;
}
message Dictionary {
   repeated Pair pairs = 1;
}
You can check the ProtoText package.
Assume you want to serialize a dict person_dict to a pre-defined PersonBuf protobuf object defined in personbuf_pb2 module. 
In this case, to use ProtoText,
import ProtoText
from personbuf_pb2 import PersonBuf
obj = PersonBuf()
obj.update(person_dict)
I firstly comment the @Flassari 's answer as it is really convenient.
However, in my case, I needed map<Type, repeated AnyModel> where :
enum Type {
    Undefined = 0;
    Square = 1;
    Circle = 2;
}
message AnyModel {
    string Name = 1;
}
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)
message MyRPCBodyCall {
    map<string, AnyModels> Models = 1;
}
enum Type {
    Undefined = 0;
    Square = 1;
    Circle = 2;
}
message AnyModel {
    string Name = 1;
}
message AnyModelArray {
    repeated AnyModel AnyModels = 1;
}
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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论