Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize anonymous type with System.Text.Json

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?

like image 374
superstator Avatar asked Dec 12 '19 21:12

superstator


People also ask

Which is better Newtonsoft JSON or System text JSON?

Json does case-insensitive property name matching by default. The System. Text. Json default is case-sensitive, which gives better performance since it's doing an exact match.

What is System JSON deserialize?

Deserializes the specified JSON string into an Apex object of the specified type. deserializeUntyped(jsonString) Deserializes the specified JSON string into collections of primitive data types. serialize(objectToSerialize) Serializes Apex objects into JSON content.

Is Newtonsoft JSON obsolete?

Obsolete. The value types allowed by the JsonSchema. JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.

Is Newtonsoft JSON still supported?

Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System.

How do I serialize an anonymous type in JSON?

Depending on your scenario, an alternative approach is to use anonymous types, like this: Basically you select properties from another object and format them as desired, and then serialize it. If you need to deserialize the JSON created from the anonymous type, you can deserialize to a dynamic object.

What is deserialize in JSON?

Deserialize (String, Type, JsonSerializerOptions) Parses the text representing a single JSON value into an instance of a specified type.

Is it possible to deserialize an anonymous type in Java?

As of . Net 5.0, deserialization of immutable types -- and thus anonymous types -- is supported by System.Text.Json. From 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.

How do I read and write JSON data without using jsonserializer?

Use the library directly, not through a framework such as ASP.NET Core. Use the JsonSerializer class with custom types to serialize from and deserialize into. For information about how to read and write JSON data without using JsonSerializer, see How to use the JSON DOM, Utf8JsonReader, and Utf8JsonWriter.


2 Answers

As of .Net 5.0, deserialization of immutable types -- and thus anonymous types -- is supported by System.Text.Json. From 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.

As anonymous types have exactly one constructor, they can now be deserialized successfully. To do so, define a helper method like so:

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
}

And now you can do:

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

Demo fiddle here.

like image 190
dbc Avatar answered Oct 21 '22 11:10

dbc


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;
like image 1
Michaël Catanzariti Avatar answered Oct 21 '22 13:10

Michaël Catanzariti