How to use class fields with System.Text.Json.JsonSerializer?(如何将类字段与 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!
}
推荐答案
在 .NET Core 3.x 中,System.Text.Json 不序列化字段.从 文档:
In .NET Core 3.x, System.Text.Json does not serialize fields. From the docs:
.NET Core 3.1 中的 System.Text.Json 不支持字段.自定义转换器可以提供此功能.
Fields are not supported in System.Text.Json in .NET Core 3.1. Custom converters can provide this functionality.
在 .NET 5 及更高版本中,可以通过设置 JsonSerializerOptions.IncludeFields
到 true
或通过标记要序列化的字段[JsonInclude]
:
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;
}
详情见:
如何在 .NET 中序列化和反序列化(编组和解组)JSON:包括字段.
问题 #34558 和 #876.
这篇关于如何将类字段与 System.Text.Json.JsonSerializer 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将类字段与 System.Text.Json.JsonSerializer 一起使用?


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01