c# - 使用 System.Text.Json 反序列化匿名类型
问题描述
我正在为 .NET Core 3.x 更新一些应用程序,作为其中的一部分,我正在尝试Json.NET
从新System.Text.Json
类迁移。使用 Json.NET,我可以像这样反序列化匿名类型:
var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
新命名空间中是否有等效方法?
解决方案
作为 。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;
演示小提琴在这里。
推荐阅读
- javascript - 在 JavaScript 中修改时,某些单选按钮不会保持选中状态
- hana - 在 Azure SQL 数据仓库中虚拟化 SAP HANA 表
- javascript - css 或 js 文件的文件大小限制
- r - 将隶属关系映射到邻接矩阵输出
- typescript - 找不到命名空间“amp”
- vba - 是否可以在没有 tnsnames.ora 文件的情况下在 Windows 10 上建立 32 位 ODBC 连接?
- json - Jackson Json Map 或 Key 反序列化器数组数据到 Java hashmap
- c# - 自定义控件样式绑定
- linux - 使用 terraform 引用在循环中创建的特定 public_ip
- c - appendStringInfo 的问题