Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse JSON string from HttpClient?

I am getting a 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": []       }     ]   },   "entities": [],   "dialog": {     "prompt": "1",     "parameterName": "1",     "parameterType": "1::1",     "contextId": "11",     "status": "1"   } }} 

I am using HttpClient. I am facing difficulty in accessing prompt key-value. I want to get prompt from dialog. How can I get it?

like image 741
Sonali Avatar asked Sep 13 '16 10:09

Sonali


People also ask

How do I parse a string in JSON?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

What is JSON parsing example?

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data.


1 Answers

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"] 
like image 193
Omar Elabd Avatar answered Oct 02 '22 18:10

Omar Elabd