How can I parse JSON string from HttpClient?
There are three ways that come to mind.
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.
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;
You can use a JObject and access its properties using strings
JObject obj = JsonConvert.DeserializeObject(result); obj["dialog"]["prompt"]
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
.
Edited :
Import Newtonsoft.Json
JObject s = JObject.Parse(result);
string yourPrompt = (string)s["dialog"]["prompt"];
By installing the NuGet package Microsoft.AspNet.WebApi.Client like this:
PM> Install-Package Microsoft.AspNet.WebApi.Client
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".