我最近将一个解决方案升级为全部 .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 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!