인터페이스로 역직렬화 하여 데이터 사용자가 가공하지 못하게 막고싶음.

하지만 인터페이스만으로는 역직렬화 할 객체가 없으므로 템플릿레코드를 추가함.

직렬화는 그대로 하면 되나, 재정의를 안할수 있는 방법이 없으므로 상속 인터페이스로 기본값 JsonConverter를 살림.

소스제너레이터나 몇가지로 좀더 개선할수 있을듯하지만 닷넷에서 근본적으로 지원해주지않고서는 더러울듯


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

[JsonConverter(typeof(JConv<IHello, JHello, Template>))]
interface JHello : IHello;
interface IHello
{
int a { get; }
string hello { get; }
protected record Template(int a, string hello) : JHello;
}

class JConv<I, J, Template> : JsonConverter<J> where J : I where Template : J
{
public override J? Read(ref Utf8JsonReader r, Type _, JsonSerializerOptions o) => JsonSerializer.Deserialize<Template>(ref r, o);
public override void Write(Utf8JsonWriter w, J v, JsonSerializerOptions o) => w.WriteRawValue(JsonSerializer.Serialize<I>(v, o));
}

class Hello : JHello
{
public int a => 1;
public string hello => "World";
}
JsonSerializer.Serialize<JHello>(new Hello()).Display();
JsonSerializer.Deserialize<JHello>("""{"a":1, "hello":"fakyu"}""")