Reputation: 4125
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
?
Upvotes: 3
Views: 1043
Reputation: 938
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);
Upvotes: 1
Reputation: 4125
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);
Upvotes: 3