C
C#6mo ago
Denis

System.Text.Json Source Generators

The JSON serialization can be optimized using source generators. I understand that I have to write a context for the given class I wish to serialize. And I'd specify the given context when serializing the class instance. What I do not understand is how I would pass the context for other classes within the serialized class? E.g.
public record Position(double X, double Y);
public record Size(int Width, int Height);

public class CanvasSettings
{
public Position ViewportLocation { get; set; }
public Size ViewportSize { get; set; }
.....
}

[JsonSerializable(typeof(CanvasSettings))]
public partial sealed CanvasSettingsContext
: JsonSerializerContext
{
}
public record Position(double X, double Y);
public record Size(int Width, int Height);

public class CanvasSettings
{
public Position ViewportLocation { get; set; }
public Size ViewportSize { get; set; }
.....
}

[JsonSerializable(typeof(CanvasSettings))]
public partial sealed CanvasSettingsContext
: JsonSerializerContext
{
}
Is the context of the CanvasSettings including data for the its property members? How can I utilize source generators when working with polymorphic types? E.g., IAnimal, Dog : IAnimal, Cat : IAnimal.
[JsonPolymorphic, JsonDerived(typeof(Dog), nameof(Dog)), JsonDerived(typeof(Cat), nameof(Cat))]
public interface IAnimal {}
[JsonPolymorphic, JsonDerived(typeof(Dog), nameof(Dog)), JsonDerived(typeof(Cat), nameof(Cat))]
public interface IAnimal {}
Do I write a context for the interface? How would the context cover all the members of the derived classes?
1 Reply
reflectronic
reflectronic6mo ago
you should not be making a new context for each class, to be clear you should just make one context for your library and put all your classes on it