I have following code:
public class Customer
{
public string CustomerName { get; set; }
[JsonConverter(typeof(ConcreteConverter<Order>))]
public List<IOrderContract> Orders { get; set; }
}
public class Order : IOrderContract {
public string OrderName { get; set; }
public string OrderType { get; set; }
}
public interface IOrderContract
{
string OrderName { get; set; }
string OrderType { get; set; }
}
When I apply patch using following code:
public IActionResult JsonPatchWithoutModelState([FromBody] JsonPatchDocument<Customer> patchDoc)
{
var customer = CreateCustomer();
patchDoc.ApplyTo(customer);
return new ObjectResult(customer);
}
private Customer CreateCustomer()
{
return new Customer
{
CustomerName = "John",
Orders = new List<IOrderContract>()
{
new Order
{
OrderName = "Order0"
},
new Order
{
OrderName = "Order1"
}
}
};
}
It throws exception that *
The value '[ { "OrderName": "name", "OrderType": "type" } ]' is invalid for target location.
*
But when I use concrete classes collection as following instead of interface:
public class Customer
{
public string CustomerName { get; set; }
public List<Order> Orders { get; set; }
}
then it works fine. I deeply dived into jsonpatchdocument and found that its unable to create instance for interface which is obvious error i.e
Could not create an instance of type IOrderContract. Type is an interface or abstract class and cannot be instantiated.
Is there any other solution for this to achieve patch conversion with interfaces?