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

不想你离开。 提交于 2019-12-17 16:57:14

问题


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!
}

回答1:


Currently, fields are not serializable. But there is a development work in progress. You can follow this thread. https://github.com/dotnet/corefx/pull/39254




回答2:


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
}


来源:https://stackoverflow.com/questions/58139759/how-to-use-class-fields-with-system-text-json-jsonserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!