使用 System.Text.Json 反序列化匿名类型

sup*_*tor 17 c# json .net-core .net-core-3.1 system.text.json

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

var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
Run Code Online (Sandbox Code Playgroud)

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

dbc*_*dbc 8

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 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
}
Run Code Online (Sandbox Code Playgroud)

And now you can do:

var token = JsonSerializerExtensions.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
Run Code Online (Sandbox Code Playgroud)

Demo fiddle here.