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);