I recently upgraded a solution to be all .NET Core 3 and I have a class that requires the class variables to be fields. This is a problem since the new System.Text.Jso
Fields now work in the prerelease version (I tried 5.0.0-rc.1.20451.14), but you have to enable the option (details in #34558 and #876):
// System.Text.Json 5.0.0-rc.1.20451.14
// 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;
}
Please try this library I wrote as an extension to System.Text.Json to offer missing features: https://github.com/dahomey-technologies/Dahomey.Json.
You will find support for fields.
using System.Text.Json;
using Dahomey.Json
public class Car
{
public int Year { get; set; } // does serialize correctly
public string Model; // will serialize correctly
}
static void Problem() {
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions(); // extension method to setup Dahomey.Json extensions
Car car = new Car()
{
Model = "Fit",
Year = 2008,
};
string json = JsonSerializer.Serialize(car, options); // {"Year":2008,"Model":"Fit"}
Car carDeserialized = JsonSerializer.Deserialize<Car>(json);
Console.WriteLine(carDeserialized.Model); // Fit
}