Skip to content

Discriminated Json Subtypes Converter implementation for .NET

License

Notifications You must be signed in to change notification settings

codenaked/JsonSubTypes

 
 

Repository files navigation

JsonSubTypes a discriminated Json sub-type Converter implementation for .NET

Build status Code Coverage Quality Gate NuGet

DeserializeObject with custom type property name

[JsonConverter(typeof(JsonSubtypes), "Kind")]
public interface IAnnimal
{
    string Kind { get; }
}

public class Dog : IAnnimal
{
    public string Kind { get; } = "Dog";
    public string Breed { get; set; }
}

class Cat : Annimal {
    bool declawed { get; set;}
}
var annimal =JsonConvert.DeserializeObject<IAnnimal>("{\"Kind\":\"Dog\",\"Breed\":\"Jack Russell Terrier\"}");
Assert.AreEqual("Jack Russell Terrier", (annimal as Dog)?.Breed);

N.B.: Also works with fully qualified type name

DeserializeObject with custom type mapping

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Annimal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Annimal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Annimal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}
var annimal =JsonConvert.DeserializeObject<IAnnimal>("{\"Sound\":\"Bark\",\"Breed\":\"Jack Russell Terrier\"}");
Assert.AreEqual("Jack Russell Terrier", (annimal as Dog)?.Breed);

N.B.: Also works with other kind of value than string, i.e.: enums, int, ...

DeserializeObject mapping by property presence

[JsonConverter(typeof(JsonSubtypes))]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
[JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Employee : Person
{
    public string Department { get; set; }
    public string JobTitle { get; set; }
}

public class Artist : Person
{
    public string Skill { get; set; }
}
string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";


var persons = JsonConvert.DeserializeObject<IReadOnlyCollection<Person>>(json);
Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);

About

Discriminated Json Subtypes Converter implementation for .NET

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%