I'm trying to write a .NET Core API that returns a list of objects. The following class is being used for sending responses:
class AnimalResponse {
public IAnimal Animal { get; set; }
}
There is an empty interface:
interface IAnimal {
}
There are also 2 classes that implement this interface:
class Cat : IAnimal {
public string CatProperty { get; set; }
}
class Dog : IAnimal {
public string DogProperty { get; set; }
}
As you can see, the Animal
property of AnimalResponse
class can contain either a Cat
or a Dog
class object. This is how I send response:
var response = new AnimalResponse() {
Animal = new Cat() {
CatProperty = "Cat Property Value"
}
};
return JsonResult(response);
For some reason CatProperty
gets missing from an API response after serialization. API returns the following json: {Animal:{}}
.
So, how do I make it include all the class-specific properties?
Note: I'm using Microsoft.AspNetCore.Mvc.JsonResult
, not Newtonsoft.Json
.