Skip to main content

How to Serialize JSON with a Source Generator and JsonSerializerContext in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Declare partial class PetJsonContext : JsonSerializerContext with [JsonSerializable(typeof(Pet))] on it, and a source generator writes the code that turns a Pet into JSON and back while the project builds. You then pass PetJsonContext.Default.Pet to JsonSerializer.

Microsoft's reference for the base class: Provides metadata about a set of types that is relevant to JSON serialization.

Without a context, JsonSerializer learns each type while the program runs. The guide: By default, JsonSerializer collects metadata at runtime by using reflection. A context moves that work to the build: You can use source generation to move the metadata collection process from runtime to compile time. During compilation, the metadata is collected and source code files are generated.

Syntax​

Syntax
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonSerializable(typeof(<Type>))]
partial class <ContextName> : JsonSerializerContext;

string <json> = JsonSerializer.Serialize(<value>, <ContextName>.Default.<Type>);
<Type> <value> = JsonSerializer.Deserialize(<json>, <ContextName>.Default.<Type>)!;
JsonSerializerOptions <options> = <ContextName>.Default.Options;
PartWhat it is
[JsonSerializable(typeof(<Type>))]A type the context handles: one line for each type you pass to JsonSerializer
partial class <ContextName> : JsonSerializerContextYour context. partial lets the source generator add the rest of the class
<ContextName>.DefaultThe guide: the static Default property of the context type provides an instance of the context type with default options.
<ContextName>.Default.<Type>The type information the generator wrote for one listed type, a JsonTypeInfo<<Type>>
<ContextName>.Default.OptionsA JsonSerializerOptions that gets every listed type from the context, for code that takes options

These follow the guide's first two steps: Create a partial class that derives from JsonSerializerContext. and Specify the type to serialize or deserialize by applying JsonSerializableAttribute to the context class.

The Example​

A console app called JsonSourceGeneration has a Pet record for an animal shelter and a context for it. It writes a dog named Rex as JSON, reads a cat named Luna from JSON, and writes a parrot through the context's options.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n JsonSourceGeneration
cd JsonSourceGeneration
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/JsonSourceGeneration/JsonSourceGeneration.csproj:
Determining projects to restore...
Restored /Users/you/source/JsonSourceGeneration/JsonSourceGeneration.csproj (in 103 ms).
Restore succeeded.

dotnet new console -n JsonSourceGeneration creates a folder named JsonSourceGeneration with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or JsonSourceGeneration.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. The record and the context go at the end of the file:

Program.cs (the record and the context)
record Pet(string Name, string Species, int Age);

// The source generator writes the rest of this class when the project builds.
[JsonSerializable(typeof(Pet))]
partial class PetJsonContext : JsonSerializerContext;

Pet is a positional record with three properties. [JsonSerializable(typeof(Pet))] tells the source generator to write the code for Pet, and partial lets it add that code to PetJsonContext, including the Default property. The class ends with ; because it has no body of its own.

At the top of the file, write a pet:

Program.cs (write a pet)
using System.Text.Json;
using System.Text.Json.Serialization;

// Write a pet as JSON with the type information the generator made for Pet.
Pet rex = new("Rex", "dog", 3);
string json = JsonSerializer.Serialize(rex, PetJsonContext.Default.Pet);
Console.WriteLine(json);

PetJsonContext.Default.Pet is the type information the generator wrote for Pet. The guide, for its own example type: The context instance provides a WeatherForecast property that returns a JsonTypeInfo<WeatherForecast> instance. Here that property is Pet.

Then read a pet:

Program.cs (read a pet)
// Read JSON back into a Pet with the same type information.
string fromShelter = """{"Name":"Luna","Species":"cat","Age":5}""";
Pet luna = JsonSerializer.Deserialize(fromShelter, PetJsonContext.Default.Pet)!;
Console.WriteLine($"{luna.Name} is a {luna.Species}, {luna.Age} years old");

JsonSerializer.Deserialize takes the same type information and returns a Pet. The ! tells the compiler the result isn't null.

Last, the context's options:

Program.cs (the options)
// Default.Options is a JsonSerializerOptions that gets its types from the context,
// for code that asks for options instead.
JsonSerializerOptions options = PetJsonContext.Default.Options;
Console.WriteLine(JsonSerializer.Serialize(new Pet("Kiwi", "parrot", 2), options));

Some methods take a JsonSerializerOptions instead of type information. PetJsonContext.Default.Options is one bound to the context. Its reference: Gets the run-time specified options of the context. If no options were passed when instantiating the context, then a new instance is bound and returned.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
{"Name":"Rex","Species":"dog","Age":3}
Luna is a cat, 5 years old
{"Name":"Kiwi","Species":"parrot","Age":2}

macOS-style terminal window titled Terminal — JsonSourceGeneration showing dotnet run printing the JSON for Rex the dog aged 3, then Luna is a cat, 5 years old, then the JSON for Kiwi the parrot aged 2

  • Rex became {"Name":"Rex","Species":"dog","Age":3} through Default.Pet.
  • Luna came back from the JSON as a Pet: a cat, 5 years old.
  • Kiwi went through Default.Options and came out with the same property names.

Default.Options only knows the context's types. A type it doesn't list throws, as Common Mistakes shows.

The Complete File​

macOS-style code window titled Program.cs — JsonSourceGeneration showing a Pet named Rex serialized with PetJsonContext.Default.Pet, JSON for Luna deserialized with the same type information, a parrot serialized through PetJsonContext.Default.Options, the Pet record, and the partial PetJsonContext class with a JsonSerializable attribute for Pet

Program.cs
using System.Text.Json;
using System.Text.Json.Serialization;

// Write a pet as JSON with the type information the generator made for Pet.
Pet rex = new("Rex", "dog", 3);
string json = JsonSerializer.Serialize(rex, PetJsonContext.Default.Pet);
Console.WriteLine(json);

// Read JSON back into a Pet with the same type information.
string fromShelter = """{"Name":"Luna","Species":"cat","Age":5}""";
Pet luna = JsonSerializer.Deserialize(fromShelter, PetJsonContext.Default.Pet)!;
Console.WriteLine($"{luna.Name} is a {luna.Species}, {luna.Age} years old");

// Default.Options is a JsonSerializerOptions that gets its types from the context,
// for code that asks for options instead.
JsonSerializerOptions options = PetJsonContext.Default.Options;
Console.WriteLine(JsonSerializer.Serialize(new Pet("Kiwi", "parrot", 2), options));

record Pet(string Name, string Species, int Age);

// The source generator writes the rest of this class when the project builds.
[JsonSerializable(typeof(Pet))]
partial class PetJsonContext : JsonSerializerContext;

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out partialThe build warned warning SYSLIB1032: Derived 'JsonSerializerContext' type 'PetJsonContext' specifies JSON-serializable types. The type and all containing types must be made partial to kick off source generation. and failed with error CS0534: 'PetJsonContext' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'Declare partial class PetJsonContext : JsonSerializerContext;
Leaving out [JsonSerializable]With no type listed, the build failed with the same error CS0534List each type: [JsonSerializable(typeof(Pet))]
Passing a type the context doesn't listA Toy through PetJsonContext.Default.Options threw NotSupportedException: JsonTypeInfo metadata for type 'Toy' was not provided by TypeInfoResolver of type 'PetJsonContext'. A List<Pet> failed the same way when only Pet was listedAdd a line for every type you pass, collections included. The guide: To specify source generation for a collection, use [JsonSerializable] with the collection type. With [JsonSerializable(typeof(List<Pet>))], PetJsonContext.Default.ListPet wrote both pets
Changing Default.Options, such as setting WriteIndentedInvalidOperationException: JsonSerializerOptions instances cannot be modified once encapsulated by a JsonSerializerContext.Set options on the context with [JsonSourceGenerationOptions], as the FAQ shows

FAQ​

How do I set options such as indented JSON?​

Put [JsonSourceGenerationOptions] on the context, next to [JsonSerializable]. The guide: The advantage to setting options via the attribute is that the configuration is specified at compile time, which ensures that the generated MyContext.Default property is preconfigured with all the relevant options set. With WriteIndented = true, Rex came out indented:

The context with options
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Pet))]
partial class PetJsonContext : JsonSerializerContext;
Output
{
"Name": "Rex",
"Species": "dog",
"Age": 3
}

Which do I pass, Default.Pet or Default.Options?​

Pass Default.Pet when you call JsonSerializer for a Pet yourself. Pass Default.Options to code that asks for a JsonSerializerOptions: it finds every type the context lists. The guide names both ways: a JsonSerializer method that Takes a JsonTypeInfo<T> instance, or one that Takes a JsonSerializerOptions instance and you've set its JsonSerializerOptions.TypeInfoResolver property to the Default property of the context type.

Conclusion​

A source-generated context is a partial class that derives from JsonSerializerContext, with a [JsonSerializable] line for each type you serialize, collections included. Pass Default.<Type> to JsonSerializer, pass Default.Options to code that asks for options, and set options such as indentation with [JsonSourceGenerationOptions] instead of changing them.

Additional Resources​