'Protobuf map unserialization issue
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?
Solution 1:[1]
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);
Solution 2:[2]
You can use Protobuf.System.Text.Json extension for System.Text.Json to fix your issue.
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sturm |
| Solution 2 | Hav |



