使用 System.Text.Json 反序列化匿名类型 [英] Deserialize anonymous type with System.Text.Json
问题描述
我正在为 .NET Core 3.x 更新一些应用程序,作为其中的一部分,我试图从 Json.NET
转移到新的 System.Text.Json
类.使用 Json.NET,我可以像这样反序列化匿名类型:
I am updating some apps for .NET Core 3.x, and as part of that I'm trying to move from Json.NET
to the new System.Text.Json
classes. With Json.NET, I could deserialize an anonymous type like so:
var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
新命名空间中是否有等效的方法?
Is there an equivalent method in the new namespace?
推荐答案
从 .Net 5.0 开始,System.Text.Json
.从 如何在 System.Text.Json 中使用不可变类型和非公共访问器:
As of .Net 5.0, deserialization of immutable types -- and thus anonymous types -- is supported by System.Text.Json
. From How to use immutable types and non-public accessors with System.Text.Json:
System.Text.Json
可以使用参数化构造函数,这使得反序列化不可变类或结构成为可能.对于一个类,如果唯一的构造函数是参数化的,则将使用该构造函数.
System.Text.Json
can use a parameterized constructor, which makes it possible to deserialize an immutable class or struct. For a class, if the only constructor is a parameterized one, that constructor will be used.
由于匿名类型只有一个构造函数,它们现在可以成功反序列化.为此,定义一个辅助方法,如下所示:
As anonymous types have exactly one constructor, they can now be deserialized successfully. To do so, define a helper method like so:
public static partial class JsonSerializerExtensions
{
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject, JsonSerializerOptions options = default)
=> JsonSerializer.Deserialize<T>(json, options);
public static ValueTask<TValue> DeserializeAnonymousTypeAsync<TValue>(Stream stream, TValue anonymousTypeObject, JsonSerializerOptions options = default, CancellationToken cancellationToken = default)
=> JsonSerializer.DeserializeAsync<TValue>(stream, options, cancellationToken); // Method to deserialize from a stream added for completeness
}
现在你可以:
var token = JsonSerializerExtensions.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
演示小提琴 此处.
这篇关于使用 System.Text.Json 反序列化匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!