I am trying to find an elegant way deserialize a complex class with an interface property whose type I want to pass at runtime.
The scenario is that I have a Web API 2 service that is consumed by a separate application using HttpClient. The service controllers produce a number of different responses that wrap a payload in a response class. The payload can be any number of separate objects that implement IPayload, and when I deserialize I need to tell the deserializer what concrete class to deserialize IPayload to.
The class looks like this:
public class Response
{
public bool Success bit {get; set;}
public IEnumerable<IPayload> Payload {get; set;}
}
And the code that attempts to deserialize
...
Response response = await hr.Content.ReadAsAsync<Response>();
...
It's almost as if I would have to pass two types to the deserializer.
I've tried to do this using TypeNameHandling, and while I can get the service to include a $type property, that won't work because the code that generates the response also utilizes a generic. I wind up with "$type": "System.Collections.Generic.List`1[[Interfaces.IPayload, ClassLibrary1]], mscorlib" which I similarly can't deserialize to a concrete class.
Is there a way to do this out of the box, or would I have to create a custom deserializer?