How can I parse json string from Httpclient

微笑、不失礼 提交于 2020-01-12 02:49:11

问题


Hi i am getting json result by calling an external api.

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = client.GetAsync(url).Result;

        if (response.IsSuccessStatusCode)
        {
            var result  = response.Content.ReadAsStringAsync().Result;
            var s = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            return "Success";
        }
        else
        {
            return "Fail";
        }

the result in line var s = Newtonsoft.Json.JsonConvert.DeserializeObject(result); I am getting is like :

 {{
  "query": "1",
  "topScoringIntent": {
    "intent": "1",
    "score": 0.9978111,
    "actions": [
      {
        "triggered": false,
        "name": "1",
        "parameters": [
          {
            "name": "1",
            "required": true,
            "value": null
          },
          {
            "name": "1",
            "required": true,
            "value": null
          },
          {
            "name": "1",
            "required": true,
            "value": null
          }
        ]
      }
    ]
  },
  "entities": [],
  "dialog": {
    "prompt": "1",
    "parameterName": "1",
    "parameterType": "1::1",
    "contextId": "11",
    "status": "1"
  }
}}

how can I get prompt of 'dialog'? I am using http client. I am facing difficulty in accessing prompt key-value. I want to get prompt from dialog. how can i get it?


回答1:


You want to have a look here: http://www.newtonsoft.com/json/help/html/deserializeobject.htm

Create a class with the same structure like your XML. Then your variable s is an instance of this class and you can deserialize the json to the class structure.

In your case your property should be s.dialog.prompt.




回答2:


There are three ways that come to mind.

  1. Assuming the json is consistent and the structure of the response will not change frequently, I would use a tool like json2csharp or jsonutils to create c# classes.

    then call:

    {GeneratedClass} obj = JsonConvert.DeserializeObject<{GeneratedClass}>(result);
    

    This will give you a strongly typed object that you can use.

  2. You can skip the class generation and use a dynamic object:

    dynamic obj = JsonConvert.DeserializeObject<dynamic>(result)
    

    and access properties such as:

    obj.dialog.prompt;
    
  3. You can use a JObject and access its properties using strings

    JObject obj = JsonConvert.DeserializeObject(result);
    
    obj["dialog"]["prompt"]
    



回答3:


Edited :

Import Newtonsoft.Json

JObject s = JObject.Parse(result);
string yourPrompt = (string)s["dialog"]["prompt"];



回答4:


With:

using Newtonsoft.Json;

you could save one step by directly reading the content as a JObject:

dynamic response = await response.Content.ReadAsAsync<JObject>();
string prompt = response.dialog.prompt.ToString();

Note: This requires the response content to be of Content-Type "application/json".



来源:https://stackoverflow.com/questions/39468096/how-can-i-parse-json-string-from-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!