How to use class fields with System.Text.Json.JsonSerializer?

In .NET Core 3.x, System.Text.Json does not serialize fields. From the docs:

Fields are not supported in System.Text.Json in .NET Core 3.1. Custom converters can provide this functionality.

In .NET 5 and later, public fields can be serialized by setting JsonSerializerOptions.IncludeFields to true or by marking the field to serialize with [JsonInclude]:

using System.Text.Json;

static void Main()
{
    var car = new Car { Model = "Fit", Year = 2008 };

    // Enable support
    var options = new JsonSerializerOptions { IncludeFields = true };

    // Pass "options"
    var json = JsonSerializer.Serialize(car, options);

    // Pass "options"
    var carDeserialized = JsonSerializer.Deserialize<Car>(json, options);

    Console.WriteLine(carDeserialized.Model); // Writes "Fit"
}

public class Car
{
    public int Year { get; set; }
    public string Model;
}

For details see:

Leave a Comment