简体   繁体   English

如何转换 REST API 响应

[英]How to transform a REST API response

I have this code which returns a REST API response.我有此代码返回 REST API 响应。 How can I parse the JSON response to loop over the array of objects?如何解析 JSON 响应以遍历对象数组?

using (HttpClient httpClient = new HttpClient())
{
    var task = httpClient.GetAsync(url.ToString());
    var res = task.Result;
    res.Content.LoadIntoBufferAsync();

    var resultTask = res.Content.ReadAsStringAsync();

    finalResponse = resultTask.Result;   // this is Json response

   // need to loop through the finalResponse??
}

My response structure from the REST API is as follows.我从 REST API 的响应结构如下。

"result": [
    {
        “maxTry: 17,
        "minTry”: 10,
        "details": [
            {
                “firstName”: “Sam”,
            },
            {
                "firstName”: ”Julio”,
            }
        ],
        "aggr": [
            “Abc”,
        ],
        "zone": “D3”
    },
    {
        "aggr": [
            "Abc",
        ],
        "zone": “C3”
    },
    {
        "aggr": [
            "Abc",
        ],
        "zone": “B2”
    },
  ]
}

The first step is to add the classes needed to deserialize Json data第一步是添加deserialize化 Json 数据所需的类

public class JsonClass
{
   public List<JResult> Result { get; set; }
}
public class JResult
{
   public string MaxTry { get; set; }
   public string MinTry { get; set; }
   public List<Names> Details { get; set; }
   public List<string> Aggr { get; set; }
   public string Zone { get; set; }
}
public class Names
{
   public string FirstName { get; set; }
}

Then download the data from the web using the following function.然后使用以下 function 从 web 下载数据。

private async Task<JsonClass> GetJsonData(string url)
{
   using (var client = new HttpClient())
   {
       var result = await client.GetAsync(url);
       var response = await result.Content.ReadAsStringAsync();
       return JsonConvert.DeserializeObject<JsonClass>(response);
   }
}

finally fetch data最后获取数据

 public JsonClass GetData(string url)
 {
     var data = Task.Run(() => GetJsonData(url)).Result;
     return data;
 }

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

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