Skip to content
/ PolyJson Public

Attribute based, polymorphic support for System.Text.Json.

Notifications You must be signed in to change notification settings

rmja/PolyJson

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PolyJson

Attribute based, polymorphic support for System.Text.Json (and optionally Newtonsoft.Json). It supports both serialization and deserialization and is reasonably fast.

Nuget Packages

Package name Description Badge
PolyJson Basic types and System.Text.Json support PolyJson
PolyJson.NewtonsoftJson Optional Newtonsoft.Json support PolyJson.NewtonsoftJson

Usage

Decorate the base class with the PolyJsonConverter attribute and register the subtypes:

[PolyJsonConverter("_t")]
//[Newtonsoft.Json.JsonConverter(typeof(PolyJsonNewtonsoftJsonConverter))] // Optional
[PolyJsonConverter.SubType(typeof(Dog), "dog")]
[PolyJsonConverter.SubType(typeof(Cat), "cat")]
public abstract class Animal
{
    [JsonPropertyName("_t")]
    //[Newtonsoft.Json.JsonProperty("_t")] // Optional
    public string Discriminator => DiscriminatorValue.Get(GetType());
    public int Id { get; set; }
}

The PolyJsonConverter specifies the discriminator field, in this case _t. And all possible sub types are registered with their discriminator value. The Newtonsoft.Json support is optional, but uses the same configured subtypes as that configured for System.Text.Json. A sub type does not have any attributes and can for example be:

public class Dog : Animal
{
    public bool CanBark { get; set; }
}

About

Attribute based, polymorphic support for System.Text.Json.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages