I have a class (Zoo) with an array of abstract objects (Animals) as one of its properties. I am trying to create a new Zoo with an API, but I can't get the Animals to deserialize correctly.
For example, my Zoo object
public class Zoo{
public string Name {get;set;} = string.Empty;
public List<Animal> ZooAnimals {get;set;} = new List<Animal>();
}
And my Animals
public abstract class Animal{
public virtual string Type {get;} = "Unset";
public bool HasBeenFed{get;set;} = false;
}
public class Sloth : Animal{
public override string Type{get;}="Sloth";
public int HoursSlept{get;set;}=0;
}
public class Dog : Animal{
public override string Type{get;}="Dog";
public string Breed{get;set;}=true;
}
I am trying to pass the following string, and I want to be able to create my zoo
{
"name":"The Zoo of Sloths and Dogs",
"animals":[
{
"type":"Sloth",
"hasBeenFed":false,
"hoursSlept":45,
}
{
"type":"Dog",
"hasBeenFed":true,
"breed":"idk but it's pretty big",
}
]
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Zoo NewZoo){
//Send my zoo to the database
}
When I try to call Post, I get the error
An error occurred while deserializing the Grammars property of class ZooApi.Models.Zoo: An error occurred while deserializing the Animals property of class ZooApi.Models.Zoo: Cannot create an instance of ZooApi.Models.Animal because it is an abstract class.
I just want to be able to get the zoo with the correct animals and their properties. How can I tell the deserializer which class to call from? And if I have to use a custom deserializer, how would I create that and how would I change [FromBody] to use that new serializer?
I've tried a few things. I noticed that if I remove the "abstract" I don't get an error. However, instead of deserializing, I just get an Animal object with only HasBeenFed set.
The other thing I've tried is that I'm using Mongodb, so I tried adding [BsonKnownTypes(typeof(Dog), typeof(Sloth)] to the top but that had no effect.