PolymorphicJsonTypeInfoResolver 7.0.15

There is a newer version of this package available.
See the version list below for details.
dotnet add package PolymorphicJsonTypeInfoResolver --version 7.0.15                
NuGet\Install-Package PolymorphicJsonTypeInfoResolver -Version 7.0.15                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PolymorphicJsonTypeInfoResolver" Version="7.0.15" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PolymorphicJsonTypeInfoResolver --version 7.0.15                
#r "nuget: PolymorphicJsonTypeInfoResolver, 7.0.15"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PolymorphicJsonTypeInfoResolver as a Cake Addin
#addin nuget:?package=PolymorphicJsonTypeInfoResolver&version=7.0.15

// Install PolymorphicJsonTypeInfoResolver as a Cake Tool
#tool nuget:?package=PolymorphicJsonTypeInfoResolver&version=7.0.15                

Polymorphic Json Type Info Resolver

nuget stryker codecov maintainability Build status

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

Installation

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

Usage

Stable contracts

Here's an example of how to use Polymorphic Json Type Info Resolver:

var options = new JsonSerializerOptions {
    TypeInfoResolver = new PolymorphicTypeInfoResolver()
        .Type<Shape>(x => x
            .DerivedTypes
            .Add<Square>("square")
            .Add<Circle>("circle"))
};
        
var json = JsonSerializer.Serialize(new Box(new Circle(10)), options);

The result will look like this:

{
    "Shape": {
        "$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).

Verify

To make sure you added all derived types of specific contract you add Verify<T>([...]) invocations:

new PolymorphicTypeInfoResolver()
    .Type<Shape>(x => x
        .DerivedTypes
        .Add<Square>("square")
        .Add<Circle>("circle")
        .Verify<Shape>() // using the assembly of Shape
        .Verify<Shape, SomeOtherLibrary.Polygon>() // using the assembly of Polygon
        .Verify<Shape>([assemblies]));
)

The verification is optional, but it saves you from runtime exceptions when serializing/deserializing data:

System.NotSupportedException 
  Runtime type 'SomeOtherLibrary.Polygon' is not supported by polymorphic type 'YourLibrary.Shape'. Path: $.Shape.

Add All Derived Types

To opt-in to all derived types from its own assembly or the specified assembly, you can use the following code:

new JsonSerializerOptions {
    TypeInfoResolver = new PolymorphicTypeInfoResolver()
        .Type<Shape>(x => x
            .DerivedTypes
            .AddAllAssignableTo<Shape>(t => t.Name)
            .AddAllAssignableTo<Shape, SomeOtherLibrary.Parallelogram>(t => t.Name)
            .AddAllAssignableTo<Shape>([assemblies], t => t.Name))
};

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 all derived types assignable to Shape from its own assembly and the assembly where Parallelogram is located with their name as the type discriminator.

Note: Using the type name for discriminator may result in unstable contracts since you will not be able to deserialize data when you change the type name as part of some refactoring! Instead consider to add all types individually and verify for completeness.

Advanced Features

To supply a factory for the polymorphic JSON options, you can use the following code:

var options = new JsonSerializerOptions {
    TypeInfoResolver = new PolymorphicTypeInfoResolver(options: () => new JsonPolymorphismOptions {
        TypeDiscriminatorPropertyName = "$TYPE"
    })
};

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!

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net7.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.27 2,387 6/7/2024
7.1.0-alpha.1 109 4/24/2023
7.0.16 1,703 4/24/2023
7.0.15 237 4/24/2023
0.1.14 203 4/24/2023
0.1.13 181 4/24/2023
0.1.12 189 4/24/2023
0.1.11 192 4/22/2023
0.1.10 182 4/21/2023
0.1.9 217 4/21/2023
0.1.8 179 4/21/2023
0.0.7 206 4/20/2023
0.0.6 198 4/20/2023
0.0.4 196 4/20/2023
0.0.3 201 4/20/2023
0.0.1 201 4/20/2023

Breaking change: using `JsonPolymorphismOptions` instead of wrapping in own builder.