C#C
C#3y ago
2 replies
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
{
}


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 {}


Do I write a context for the interface? How would the context cover all the members of the derived classes?
Was this page helpful?