Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.Net JsonSerializer does not serialize tuple's values

JSON serializer returns an empty JSON object.

using System.Text.Json;

(int, int) tuple1 = (1, 2);
var token = JsonSerializer.Serialize(tuple1); // return empty object {}

(int item1, int item2) tuple2 = (1, 2);
token = JsonSerializer.Serialize(tuple2); // return empty object {}

(int item1, int item2) tuple3 = (item1:1, item2:2);
token = JsonSerializer.Serialize(tuple3); // return empty object {}

it can be passed by many workarounds

I’m trying to understand why or what prevents the serializer to understands the tuples

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is it related to the tuples’ structure

>Solution :

A ValueTuple doesn’t have properties, only public fields. Until .NET 6, System.Text.Json only serialized public properties. This is the most common case, as fields are considered implementation, not part of an object’s API. All serializers prioritize properties over fields unless instructed to also serialize fields.

.NET 6 added the ability to serialize fields in a similar way to other serializer, either with an attribute over a field or a serializer setting.

Since we can’t add attributes to a tuple field, we can use settings:

var options = new JsonSerializerOptions
{
    IncludeFields = true,
};
var json = JsonSerializer.Serialize(tuple1, options);

This produces :

 {"Item1":1,"Item2":2}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading