I'm trying to serialize the IAnimal instance object to json using Json.NET. Class structure:
public class Dog : IAnimal {
public int Width { get; set; }
public double Bark { get; set; }
}
public class Cat : IAnimal {
public int Width { get; set; }
public double Meow { get; set; }
}
public interface IAnimal {
int Width { get; set; }
}
public class AnimalContainer {
public IAnimal Animal { get; set; }
}
Tried this way (please notice I use 'TypeNameHandling.Auto' as I found in other threads):
public void IAnimal_ShouldBeJsonSerializable() {
var animal = new AnimalContainer {Animal = new Dog {Bark = 5, Width = 2}};
var json = JsonConvert.SerializeObject(animal,
new JsonSerializerSettings{TypeNameHandling = TypeNameHandling.Auto});
var deserializedAnimal = JsonConvert.DeserializeObject<AnimalContainer>(json);
}
but is throwing me exception that "Could not create an instance of type IAnimal, Type is an interface or abstract class and cannot be instantiated". But the json contains the concrete type information!
How can I make it work?