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
}
And now you can do:
var token = JsonSerializerExtensions.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
Demo fiddle here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…