Skip to content

Latest commit

 

History

History
80 lines (56 loc) · 3.29 KB

README.md

File metadata and controls

80 lines (56 loc) · 3.29 KB

Serialization for advanced .NET types

License Donate Solana

The Hexarc Serialization project provides additional converters for the System.Text.Json serializer.

Packages

Package Platform Version Downloads
Hexarch.Serialization.Union .NET 7.0+ NuGet Downloads
Hexarch.Serialization.Tuple .NET 7.0+ NuGet Downloads

Hexarc.Serialization.Union

The Hexarc.Serialization.Union package helps to serialize .NET/C# classes hierarchy as a tagged union (also known as a discriminated union).

A tagged union example

[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.

Serialization and deserialization of the tagged union

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.

Hexarc.Serialization.Tuple

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}");

Acknowledgments

Built with JetBrains tools for Open Source projects.

JetBrains Logo (Main) logo

License

MIT © Hexarc Software and its contributors