简体   繁体   中英

Using HttpContent.ReadAsAsync<T> to parse responses with one object or an array

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.

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[]>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM