Home > Software engineering >  .Net JsonSerializer does not serialize tuple's values
.Net JsonSerializer does not serialize tuple's values

Time:12-22

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

is it related to the tuples' structure

CodePudding user response:

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}
  • Related