Reputation: 168
I'm integrating to an API that returns this model from almost endpoints
{
meta: { ... },
data: { ... }
}
But for some calls, the data is an array of the same kind of objects
{
meta: { ... },
data: [
{ ... },
{ ... }
]
}
I want to use HttpContent.ReadAsAsync<ResponseObj>
to convert both of these to my C# classes, and the I've set up the Response class like this:
public class ResponseObj {
public MetaObj Meta {get;set;}
public DataObj[] Data {get;set;}
}
Somewhat expectedly, I get an exception when trying to parse the first response. Is it possible to tell the JSON parser to handle the single data object and return a single-element array?
The only other solution I can see is to create separate ResponseObj
definitions for the two different response types.
Upvotes: 3
Views: 567
Reputation: 1634
Create your ResponseObj as a generic class.
public class ResponseObj<T> {
public MetaObj Meta {get;set;}
public T Data {get;set;}
}
You can deserialize json using HttpContent.ReadAsAsync<ResponseObj<DataObj>>
or HttpContent.ReadAsAsync<ResponseObj<DataObj[]>>
Upvotes: 2