Configure polymorphism with the contract model
License
—
Deps
0
Install Size
—
Vulns
✓ 0
Published
Jun 7, 2024
$ dotnet add package PolymorphicJsonTypeInfoResolverPolymorphic Json Type Info Resolver allows you to configure polymorphism on the contract model without polluting the domain model with attributes. This library leverages the polymorphic type serialization feature introduced in .NET7.
In version 8, the automatic inclusion of all subtypes for a specified type and the validation logic have been removed. This change simplifies the library and reduces its scope. These features may be reintroduced in separate packages in the future, but for now, they are not part of this library.
What does this mean for you?
With<T> method as shown in the usage section below.Type has been renamed to With.Build method.You can install the Polymorphic Json Type Info Resolver via NuGet Package Manager or by using the .NET CLI.
NuGet Package Manager:
1. Search for "PolymorphicJsonTypeInfoResolver" in the NuGet Package Manager in Visual Studio.
2. Click "Install".
.NET CLI:
dotnet add package PolymorphicJsonTypeInfoResolver
Define your domain model:
record Box(Shape Something);
interface Shape;
record Square(double Length) : Shape;
record Circle(double Radius) : Shape;
Here's an example of how to use Polymorphic Json Type Info Resolver:
var options = new JsonSerializerOptions {
TypeInfoResolver = new PolymorphicJsonTypeInfoResolver.Builder()
.With<Shape>(x => x
.DerivedTypes
.Add<Square>("square")
.Add<Circle>("circle"))
.Build()
};
var json = JsonSerializer.Serialize(new Box(new Circle(10)), options);
The result will look like this:
{
"Something": {
"$type":"circle",
"Radius":10
}
}
In the above code snippet, we create a new instance of JsonSerializerOptions and set its TypeInfoResolver property to an instance of PolymorphicTypeInfoResolver. We then configure the resolver to serialize objects of type Shape with a $type property that specifies the derived type (Square or Circle).
For advanced configurations, you can specify the full JsonPolymorphismOptions when specifying a type:
new Builder()
.With<Shape>(new JsonPolymorphismOptions {
TypeDiscriminatorPropertyName = "$TYPE",
DerivedTypes = {
new JsonDerivedType(typeof(Circle), "circle")
}
})
.Build()
Note: It is not possible to use the cleaner syntax Add in this context.
To supply a factory for the polymorphic json options, you can use the following code:
new Builder(() => new JsonPolymorphismOptions {
TypeDiscriminatorPropertyName = "$TYPE"
})
.With<Shape>(...)
.Build()
In the above code snippet, we create a new instance of JsonSerializerOptions and set its TypeInfoResolver property to an
instance of PolymorphicTypeInfoResolver. We then supply a factory function that returns an instance of JsonPolymorphismOptions
with a custom $TYPE type discriminator property name.
Remark: this readme was peer-reviewed by ChatGPT.
Happy coding!