使用System.Text.Json反序列化匿名类型 [英] Deserialize anonymous type with System.Text.Json

查看:493
本文介绍了使用System.Text.Json反序列化匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am updating some apps for .NET Core 3.x, and as part of that I'm trying to move from Json.NET to the new System.Text.Json classes. With Json.NET, I could deserialize an anonymous type like so:

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

新名称空间中是否存在等效方法?

Is there an equivalent method in the new namespace?

推荐答案

请尝试使用我作为System.Text.Json的扩展编写的该库,以提供缺少的功能: https://github.com/dahomey-technologies/Dahomey.Json

Please try this library I wrote as an extension to System.Text.Json to offer missing features: https://github.com/dahomey-technologies/Dahomey.Json.

您会发现支持匿名类型。

You will find support for anonymous types.

通过调用JsonSerializerOptions来设置命名空间Dahomey.Json中定义的扩展方法SetupExtensions的json扩展:

Setup json extensions by calling on JsonSerializerOptions the extension method SetupExtensions defined in the namespace Dahomey.Json:

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();

然后使用JsonSerializerExtensions静态类型序列化您的类:

Then serialize your class with the JsonSerializerExtensions static type:

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

这篇关于使用System.Text.Json反序列化匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆