如何在System.Text.Json.JsonSerializer中使用类字段? [英] How to use class fields with System.Text.Json.JsonSerializer?

查看:585
本文介绍了如何在System.Text.Json.JsonSerializer中使用类字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将解决方案升级为全部.NET Core 3,并且我有一个类,要求类变量为字段.这是一个问题,因为新的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!
}

推荐答案

当前,字段不可序列化.但是正在进行开发工作.您可以关注此线程.

Currently, fields are not serializable. But there is a development work in progress. You can follow this thread.

这篇关于如何在System.Text.Json.JsonSerializer中使用类字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆