How to serialize a Dictionary in C# using protobuf?

Viewed 73

Is it possible to serialize a dictionary using protobuf?

At a high level, I have a function written using Lua that contains a table:

function DM()
  
    config = {
        stop_sign = 0.60, 
        traffic_signal = 0.80
        }
        
    UDC:publishAIMLConfig("config")
    
UDC:aimlEventImageDataReq('aimldatacollection',1,priorityLevel,cameraID,resolution,1,5,5,uplink)
end

On C#, I have a function that it is receiving the values from the table and storing them into a Dictionary of type <object, object> and printing them out. But what I really would like to do is receive these values, serialize them and send it via MQTT to another application.

public void publishAIMLConfig(string inputTable)
{
    LuaTable tb = Form1.state.GetTable(inputTable);

    Dictionary<object, object> dict = Form1.state.GetTableDict(tb);

    foreach (KeyValuePair<object, object> de in dict)
    {
        Console.WriteLine("{0} {1}", de.Key.ToString(), de.Value.ToString());
    }
}

Q: is there a way to serialize objects inside the C# dictionary and if so, how would the proto file looks like?

1 Answers

The real problem here isn't the dictionary - it is the object usage. Protobuf for not include type metadata (unless you use Any), which means that both ends need to agree on what they're sending and receiving in advance. This isn't possible for something like an object/object map. There are some ways of handling a known set of types in protobuf - essentially via oneof - but that requires you to determine the possible types in advance and effectively change your structure such that you're dealing with a type that has the oneof member. Finally, note that map in protobuf is only defined for primitive and fixed (meaning: not oneof) key types; you can still do something similar if you need more flexibility, but you'd need to write your own "key value pair" message type where the key and value are the type that has a oneof.

Related