The Hexarc Serialization project provides additional converters for the System.Text.Json
serializer.
Package | Platform | Version | Downloads |
---|---|---|---|
Hexarch.Serialization.Union |
.NET 7.0+ | ||
Hexarch.Serialization.Tuple |
.NET 7.0+ |
The Hexarc.Serialization.Union
package helps to serialize .NET/C# classes hierarchy as a tagged union (also known as a discriminated union).
[UnionTag(nameof(Kind))]
[UnionCase(typeof(Circle), nameof(Circle))]
[UnionCase(typeof(Square), nameof(Square))]
public abstract class Shape
{
public abstract String Kind { get; }
}
public sealed class Circle : Shape
{
public override String Kind { get; } = nameof(Circle);
public required Double Radius { get; set; }
}
public sealed class Square : Shape
{
public override String Kind { get; } = nameof(Square);
public required Double Side { get; set; }
}
In the example above the UnionTag
attribute marks the union tag and the UnionCase
attribute
marks a known subtype (or a case class) of the Shape
class.
var settings = new JsonSerializerOptions { Converters = { new UnionConverterFactory() } };
var square = new Square { Side = 15.0 };
Console.WriteLine(JsonSerializer.Serialize(square, settings));
var shape = JsonSerializer.Deserialize<Shape>(@"{ ""Kind"": ""Circle"", ""Radius"": 10.0 }", settings);
Console.Write((shape as Circle)!.Radius);
Some technical details about the tagged union converter implementation can be found in this article.
The Hexarc.Serialization.Tuple
package helps to serialize .NET/C# value tuple types.
var settings = new JsonSerializerOptions { Converters = { new TupleConverterFactory() } };
var point = (10, 20);
Console.WriteLine(JsonSerializer.Serialize(point, settings));
var (x, y) = JsonSerializer.Deserialize<(Int32, Int32)>(@"[10, 20]", settings);
Console.Write($"Point coords: {x}, {y}");
Built with JetBrains tools for Open Source projects.