[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
[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, ...
[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);