Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created April 14, 2026 13:29
Show Gist options
  • Select an option

  • Save einarwh/18bfbe671d70dec0740d9172a67687d3 to your computer and use it in GitHub Desktop.

Select an option

Save einarwh/18bfbe671d70dec0740d9172a67687d3 to your computer and use it in GitHub Desktop.
public class CustomerBlobJsonConverter : JsonConverter<CustomerDto20260303>
{
public override CustomerDto20260303 Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
var root = JsonSerializer.Deserialize<JsonElement>(ref reader);
var schema = root.GetProperty("$schema").GetString();
return schema switch
{
CustomerDto20260303.SchemaName => root.Deserialize<CustomerDto20260303>(GetSerializerOptions()),
CustomerDto20260202.SchemaName => Upgrade(root.Deserialize<CustomerDto20260202>(GetSerializerOptions())),
CustomerDto20260101.SchemaName => Upgrade(Upgrade(root.Deserialize<CustomerDto20260101>(GetSerializerOptions()))),
_ => throw new Exception($"Unsupported schema {schema}")
};
}
public override void Write(
Utf8JsonWriter writer,
CustomerDto20260303 dto,
JsonSerializerOptions options)
{
var jsonDoc = JsonSerializer.SerializeToDocument(dto, GetSerializerOptions());
var jsonObj = JsonObject.Create(jsonDoc.RootElement);
jsonObj.Add("$schema", CustomerDto20260303.SchemaName);
JsonSerializer.Serialize(writer, jsonObj, GetSerializerOptions());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment