Search code examples
c#jsongrpc

How to deserialize json to protobuf that contains collections?


I have a json file that I would like to deserialize to a C# protobuf object. I'm able to deserialize the json, however any repeated fields are not preserved and are instead null, I believe this is related to how the protobuf objects are represented in c# with readonly fields.

{
  "Name": "Anna",
  "PlacesTravelled": [
    {
      "Country": "Spain",
      "City": "Barcelona"
    },
    {
      "Country": "England",
      "City": "London"
    }
  ]
}
message Person {
    string name = 1;
    repeated Location PlacesTravelled = 2;
}

message Location {
    string Country = 1;
    string City = 2;
}

enter image description here


Solution

  • You might try this solution:

    using System;
    using Google.Protobuf;
    ...
    var message = (IMessage)Activator.CreateInstance(typeof(YOUR_CLASS));
    var result = (YOUR_CLASS)JsonParser.Default.Parse(json, message?.Descriptor);