首页 > 解决方案 > 使用 System.Text.Json 反序列化匿名类型

问题描述

我正在为 .NET Core 3.x 更新一些应用程序,作为其中的一部分,我正在尝试Json.NET从新System.Text.Json类迁移。使用 Json.NET,我可以像这样反序列化匿名类型:

var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;

新命名空间中是否有等效方法?

标签: c#json.net-coresystem.text.json.net-core-3.1

解决方案


作为 。NET 5.0中,不可变类型的反序列化 - 以及匿名类型 - 由System.Text.Json. 从How to use immutable types and non-public accessors with System.Text.Json

System.Text.Json可以使用参数化构造函数,这使得反序列化不可变类或结构成为可能。对于一个类,如果唯一的构造函数是参数化构造函数,则将使用该构造函数。

由于匿名类型只有一个构造函数,它们现在可以成功反序列化。为此,请定义一个辅助方法,如下所示:

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;

演示小提琴在这里


推荐阅读