I have a solution that contains a Web API and an MVC Web application.
My API has this entity model, with an abstract parent class and a couple child classes:
public abstract class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Student : Person
{
public Address Dormitory { get; set; }
... additional fields
}
public class Professor : Person
{
public Schedule OfficeHours { get; set; }
... additional fields
}
I have an endpoint to get all Persons:
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Person>), (int)HttpStatusCode.OK)]
public async Task<IActionResult> GetPersons()
{
var persons = await _dbContext.Persons.ToListAsync();
return Ok(persons);
}
This which works great with Entity Framework, it returns a collection of both Students and Professors, with their properties.
My web application is calling this API. The web project has view models, that are basically the same as the entity models in the API. Here's the method that attempts to call the API and deserialize the results:
public async Task<IEnumerable<PersonViewModel>> GetPersons()
{
var data = await _apiClient.GetStringAsync(_personsUri);
var response = JsonConvert.DeserializeObject<IEnumerable<PersonViewModel>>(data);
return response;
}
The problem is that I can't deserialize to my view model, I get an exception saying:
JsonSerializationException: Could not create an instance of type PersonViewModel. Type is an interface or abstract class and cannot be instantiated.
And if I remove abstract
from my PersonViewModel, it only returns those objects, and doesn't contain the properties for Students or properties for Professors.
Is there another way I can do this?