问题
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