Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.Json.JsonSerializer doesn't support serializing nor deserializing fields but only handles properties instead.

Is there any way to ensure that the two final classes in the example below have the same exact values?

using System.Text.Json;

public class Car
{
    public int Year { get; set; } // does serialize correctly
    public string Model; // doesn't serialize correctly
}

static void Problem() {
    Car car = new Car()
    {
        Model = "Fit",
        Year = 2008,
    };
    string json = JsonSerializer.Serialize(car); // {"Year":2008}
    Car carDeserialized = JsonSerializer.Deserialize<Car>(json);

    Console.WriteLine(carDeserialized.Model); // null!
}
like image 836
BillHaggerty Avatar asked Sep 27 '19 18:09

BillHaggerty


People also ask

Which one is correct class for JSONSerializer?

The JsonSerializer is a static class in the System. Text. Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.

What is JSON property in C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

How do you serialize and deserialize an object in C# using JSON?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

How do I deserialize a string in C#?

Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method. For the generic overloads, you pass the type of the class you created as the generic type parameter. For the non-generic overloads, you pass the type of the class you created as a method parameter.


1 Answers

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:

  • How to serialize and deserialize (marshal and unmarshal) JSON in .NET: Include fields.

  • Issues #34558 and #876.

like image 80
pavinan Avatar answered Oct 21 '22 22:10

pavinan