Thursday, September 28, 2023
HomeC#System.Textual content.Json Serializing Hierarchical Knowledge –

System.Textual content.Json Serializing Hierarchical Knowledge –

The System.Textual content.Json serializer that was launched with .NET Core 3.0 will get new options with each new .NET model. With .NET 7, options corresponding to sort hieararchies, contract customization, and supply generator options have been added. This text exhibits utilizing the JSON serializer with a hierarchy, and utilizing a supply generator.

The Mannequin

The mannequin that’s outlined defines the categories Recreation, and Transfer. The Recreation class specifies a couple of easy properties in addition to a property of sort ICollection<Transfer> that specifies a relationship. Utilizing the first constructor syntax, the C# compiler creates init-only properties with C# class data and a constructor that initializes the properties. The Strikes property of sort ICollection<Transfer> is initialized with a Checklist<Transfer>. On this scneario, the gathering incorporates sorts deriving from the summary Transfer class.

The hierarchy is created with the Transfer sort. The generic model Transfer<T> derives from the non-generic summary Transfer class. The Transfer<TField> class specifies a property of sort ICollection<TField> that has a set of fields of a single recreation transfer. The sort TField is a generic parameter which permits utilizing totally different recreation sorts. For instance, a transfer can include an inventory of various colours, or with one other recreation sort, an inventory of various shapes and colours. The values of the Transfer class in addition to the generic lessons deriving from it must be written to the serialized JSON content material.

The categories that shall be used for the generic sort parameter TField are the data ColorField and ShapeAndColorField. ColorField wraps a colour specified by a string, ShapeAndColorField wraps two strings specifying a form and a colour.


To serialize the derived lessons to JSON, the deserializer must know the categories to create. To permit this, the JsonPolymorphic attribute is used to specify a key that’s saved on serialization with the JSON content material. With the pattern code, the title $discriminator is used for the important thing. The values for this discriminator are specified with the JsonDerivedType attribute. JsonDerivedType is utilized to the bottom class Transfer to specify what derived sorts must be serialized, and what discriminator worth must be used with serialization. Utilizing deserialization the worth is used to create an occasion of the mapped class.

As a result of the Strikes property of the Recreation class is required with deserialization, the get accessor is just not sufficient. Within the code pattern, a personal init accessor along with the JsonInclude attribute is used.

JSON Serialization

The mannequin sorts are in place, subsequent let’s create and serialize situations with JsonSerializer.Serialize. The serialization is custom-made passing JsonSerializerOptions. With the pattern code, the naming coverage is about to camel case which is identical configuration used from a Net API. For a nicer output on the console, write indented is configured. Invoking JsonSerializer.Deserialize, .NET objects are created from JSON:

JSON Serialization

Checking the output data, you may see the $discriminator and the values used specified from the attribute:

JSON output

JSON Supply Generator

To scale back reflection and as an alternative generate supply code at compile time, the JSON supply generator can be utilized. This generator is activated by creatign a partial class that derives from the bottom class JsonSerializerContext, and annoatating it with the JsonSourceGenerationOptions. The GamesContext class within the following code snippet makes use of the identical settings because the JsonSerializerOptions with the earlier pattern.

JSON Source Generator Context

Opposite to the earlier pattern utilizing properties with init accessors, this isn’t doable with the .NET 7 JSON supply generator. The .NET 7 supply generator doesn’t help init accessors and required modifiers. Utilizing preview 1 of .NET 8, that is already doable. See a hyperlink under for upcoming System.Textual content.Json updates with .NET 8.

To make use of the generated supply code, the context must be handed as an argument of the Serialize and Deserialize strategies as proven within the subsequent code snippet. The GamesContext.Default property is created from the supply generator.

Use the source generator

To verify the generated code, you may open the Visible Studio Resolution Explorer, open Analyzers bewlow Dependencies, and increase the System.Textual content.Json.SourceGeneration. Right here you discover how all of the totally different attributes apply to supply code.

Source generator generated code

Take away

Whereas the primary model of System.Textual content.Json was very quick, it was restricted with its options. Each .NET model since then, the JSON serializer has been enhanced. With .NET 7 it helps a hierarchy of lessons by making use of easy attributes. This serializer reduces reminiscence wants and enhances efficiency by utilizing the Span sort. With the supply generator, extra efficiency imporovements are doable, and the way in which will get opened for utilizing AOT compilation with .NET 8.

Take pleasure in studying and programming!


When you like this text, please purchase Christian a cup of espresso by going right here. Thanks!



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments