简体   繁体   English

使用 HttpContent.ReadAsAsync<t> 使用一个 object 或数组解析响应</t>

[英]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我正在集成到从几乎端点返回此 model 的 API

{
  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:我想使用HttpContent.ReadAsAsync<ResponseObj>将这两个转换为我的 C# 类,并且我已经像这样设置了响应 class :

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?是否可以告诉 JSON 解析器处理单个数据 object 并返回一个单元素数组?

The only other solution I can see is to create separate ResponseObj definitions for the two different response types.我能看到的唯一其他解决方案是为两种不同的响应类型创建单独的ResponseObj定义。

Create your ResponseObj as a generic class.将您的 ResponseObj 创建为通用 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[]>>您可以使用HttpContent.ReadAsAsync<ResponseObj<DataObj>>HttpContent.ReadAsAsync<ResponseObj<DataObj[]>>反序列化 json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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