I have tried to implement Source Generation-based JSON serilization, based on this article :
My code is the following :
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. I don't understand why.
Any clue about this ?
CodePudding user response:
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.
You cannot yet easily inspect or debug generated source from Visual Studio. You can 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);