Consider the following .proto definition:
syntax = "proto3";
option csharp_namespace = "Test";
message Book
{
string name = 1;
map<string, PersonInfo> persons = 2;
}
message PersonInfo
{
string name = 1;
string details = 2;
}
I want to serialize to a file an instance of Book and later deserialize it:
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var book1JsonStr = JsonSerializer.Serialize(book1);
//unserialization
var book2 = JsonSerializer.Deserialize<Book>(book1JsonStr);
The object book1 is populated correctly:

And the serialized string is also correct:

The issue arises when we unserialize the object back:

"Regular" fields (string, double, int) are unserialized, but the map (Google.Protobuf.Collections.MapField<TKey, TValue>) it is not. Why this is happening? Is this a bug?
What can I do to unserialize a MapField?
Using Newtonsoft.Json instead of System.Text.Json solved this issue.
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var book1JsonStr = JsonConvert.SerializeObject(book1);
//unserialization
var book2 = JsonConvert.SerializeObject<Book>(book1JsonStr);
You can use Protobuf.System.Text.Json extension for System.Text.Json to fix your issue (which can be found as a NuGet package).
var book1 = new Book() { Name = "Book1" };
book1.Persons.Add("Person1", new PersonInfo() { Name = "Person1", Details = "Some details" });
//serialization
var jsonSerializerOptions = new JsonSerializerOptions();
jsonSerializerOptions.AddProtobufSupport();
var book1JsonStr = JsonSerializer.Serialize(book1, jsonSerializerOptions);
//deserialization
var book2 = JsonSerializer.Deserialize<Book>(book1JsonStr, jsonSerializerOptions);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With