I need to read a value from HTTP response. Here is an example of the response in which I’m trying to fetch (description) value:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9@2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
Here is my code
Dictionary<string, dynamic> responseData;
string data = "entityId=8a8294174d0595bb014d05d82e5b01d2";
string url = "https://test.oppwa.com/v1/checkouts/" + CheckoutId + "/payment?" + data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = "Bearer xxxx";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// var s = new JavaScriptSerializer();
responseData = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(reader.ReadToEnd());
reader.Close();
dataStream.Close();
}
// If responseDate.Description=success then enroll user and register the payment
var res = responseData["result"];
// I'm trying to do this but not working
var res = responseData["result"]["description"];
return responseData;
Any help is appreciated
Thanks
3
Answers
Will get you the JValue of "successful".
Although there are some other issues. Deserialize needs an instance of JsonSerializer, it is not a static method. Here is a full example without using a Dictionary.
You can use
JToken
orJObject
ofNewtonsoft.Json.Linq
.For example, if your response format like as below:
You can use below code for this purpose:
For more details, you can visit this links:
Using JSON.NET for dynamic JSON parsing
Querying JSON with dynamic
What is better to use when parsing dynamic JSON data: JToken or c# built in dynamic type
try this
description value