Skip to content

Commit

Permalink
Update serialization sample (#168)
Browse files Browse the repository at this point in the history
* Update serialization sample.
* Add serialization example to readme.
  • Loading branch information
domn1995 authored Sep 15, 2023
1 parent 60fc3a3 commit d44d7f9
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
47 changes: 47 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,53 @@ public static bool IsThreeDimensional(this Shape shape) =>
);
```

## Serialization/Deserialization

```cs
using Dunet;
using System.Text.Json.Serialization;

// Serialization and deserialization can be enabled with the `JsonDerivedType` attribute.
[Union]
[JsonDerivedType(typeof(Circle), typeDiscriminator: nameof(Circle))]
[JsonDerivedType(typeof(Rectangle), typeDiscriminator: nameof(Rectangle))]
[JsonDerivedType(typeof(Triangle), typeDiscriminator: nameof(Triangle))]
public partial record Shape
{
public partial record Circle(double Radius);
public partial record Rectangle(double Length, double Width);
public partial record Triangle(double Base, double Height);
}
```

```cs
using System.Text.Json;
using static Shape;

var shapes = new Shape[]
{
new Circle(10),
new Rectangle(2, 3),
new Triangle(2, 1)
};

var serialized = JsonSerializer.Serialize(shapes);

// NOTE: The type discriminator must be the first property in each object.
var deserialized = JsonSerializer.Deserialize<Shape[]>(
//lang=json
"""
[
{ "$type": "Circle", "radius": 10 },
{ "$type": "Rectangle", "length": 2, "width": 3 },
{ "$type": "Triangle", "base": 2, "height": 1 }
]
""",
// So we recognize camelCase properties.
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }
);
```

## Pretty Print

To control how union variants are printed with their `ToString()` methods, override and seal the union declaration's `ToString()` method. For example:
Expand Down
27 changes: 25 additions & 2 deletions samples/Serialization/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,33 @@
var shapes = new Shape[] { circle, rectangle, triangle };

var shapesJson = JsonSerializer.Serialize(shapes);
var deserializedShapes = JsonSerializer.Deserialize<Shape[]>(shapesJson);

Console.WriteLine(shapesJson);

// NOTE: The type discriminator must be the first property.
var deserializedShapes = JsonSerializer.Deserialize<Shape[]>(
//lang=json
"""
[
{
"$type": "Circle",
"radius": 10
},
{
"$type": "Rectangle",
"length": 10,
"width": 10
},
{
"$type": "Triangle",
"base": 10,
"height": 10
}
]
""",
// So we recognize camelCase properties.
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }
);

foreach (var shape in deserializedShapes!)
{
Console.WriteLine(shape);
Expand Down

0 comments on commit d44d7f9

Please sign in to comment.