Search code examples
c#.netsystem.text.jsonsourcegenerators

Where does .NET 6's System.Text.Json source generation store its code?


I have tried to implement Source Generation-based JSON serilization, based on MS Docs: How to use source generation in System.Text.Json. My code is as follows:

using System;
using System.Text.Json;

var person = new Person(){FirstName = "John", LastName = "Shepard"};
Console.WriteLine(JsonSerializer.Serialize(person));

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And my SerializationContext:

[JsonSerializable(typeof(Person))]
public partial class PersonJsonContext : JsonSerializerContext
{

}

I have the System.Text.Json version 6.0.0 installed in my project.

But when running dotnet build, no code is generated in my PersonJsonContext class. Where can I find the generated code?


Solution

  • A source generator generates source code in as an intermediate compilation step. As input, it has your code annotated with opt-in attributes, and as output it has C# files that will get compiled into your final assembly.

    Using Visual Studio 2019 version 16.9 or higher you can expand the Analyzers section under the Dependencies of your project tree to see the generated code: Dependencies -> Analyzers

    You can also browse the files by opening your output directory, the .g.cs files should be in the obj directory by default.

    Now the [JsonSerializable] attribute opt-in for the System.Text.Json serializers makes the compiler output classes that aid in serialization, so you won't take a performance hit when you first serialize or deserialize to or from a certain class, but offload this performance hit to the compilation phase.

    Without code generators, System.Text.Json inspects the type for serialization metadata when it first encounters a type, caching it for the remainder of the application lifetime.

    If you apply the appropriate attributes and inspect your output directory, and you actually use the context during (de)serialization, you'll notice when it didn't work.

    Just be sure to pass the context for the appropriate type:

    var json = JsonSerializer.Serialize(person, PersonJsonContext.Default.Person);