Deserialize anonymous type with System.Text.Json

泄露秘密 提交于 2020-01-14 13:55:11

问题


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?


回答1:


As pointed out by dbc above, this just isn't possible currently. We looked at JsonDocument as a workaround, but it's also missing things like case insensitivity for property names.

So, looks like we'll be sticking to Json.NET for now.




回答2:


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.

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

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

Then serialize your class with the JsonSerializerExtensions static type:

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


来源:https://stackoverflow.com/questions/59313256/deserialize-anonymous-type-with-system-text-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!