I have a web method that returns a collection of objects which have a property that is an abstract class. There are three types that derive from the abstract class.
public enum VehicleType { Train, Truck, Boat }
public abstract class Vehicle
{
public VehicleType VehicleType { get; set; }
...
}
public class Train : Vehicle { ... }
public class Truck : Vehicle { ... }
public class Boat : Vehicle { ... }
public class Shipment
{
public Vehicle TransportVehicle { get; set; }
}
[HttpGet]
[Route("{customerId}/shipments")]
public async Task<ActionResult<ShipmentsResponse>> GetCustomerShipments(intcustomerId, CancellationToken cancellationToken)
{
...
// Returns a ShipmentResponse which contains a collection of Shipment objects
}
When the result is received by the client, JSON.NET attempts to deserialize the collection and throws this exception:
Could not create an instance of type Management.Domain.Models.Vehicle. Type is an interface or abstract class and cannot be instantiated. Path 'data.shipments[0].vehicle.vehicleType', line 1, position 462.
So I figured I could use a CustomCreationConverter for the Vehicle type:
public class VehicleConverter : CustomCreationConverter<Vehicle>
{
private VehicleType _currentVehicleType;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.ReadFrom(reader);
_currentScheduleType = jObject["VehicleType"].ToObject<UserScheduleType>();
return base.ReadJson(jObject.CreateReader(), objectType, existingValue, serializer);
}
public override VehicleCreate(Type objectType)
{
switch (_currentVehicleType)
{
case VehicleType.Train:
return new Train();
case VehicleType.Truck:
return new Truck();
case VehicleType.Boat:
return new Boat();
default:
throw new NotImplementedException();
}
}
}
...but this code is never hit. Can anyone shed some light on how I can resolve this? Thanks for any advice!