我正在更新.NET Core 3.x的一些应用程序,作为其中的一部分,我试图从Json.NET
移到新的System.Text.Json
类。使用Json.NET,我可以反序列化匿名类型,如下所示:
var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
新 namespace 中是否存在等效的方法?
最佳答案
作为 。 Net 5.0 ,System.Text.Json
支持不可变类型(进而是匿名类型)的反序列化。从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.
由于匿名类型只有一个构造函数,因此它们现在可以成功反序列化。为此,请定义一个辅助方法,如下所示:
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;
演示 fiddle here。
关于c# - 使用System.Text.Json反序列化匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313256/