I have this code which returns a REST API response. How can I parse the JSON response to loop over the array of objects?
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.
"result": [
{
“maxTry: 17,
"minTry”: 10,
"details": [
{
“firstName”: “Sam”,
},
{
"firstName”: ”Julio”,
}
],
"aggr": [
“Abc”,
],
"zone": “D3”
},
{
"aggr": [
"Abc",
],
"zone": “C3”
},
{
"aggr": [
"Abc",
],
"zone": “B2”
},
]
}
CodePudding user response:
The first step is to add the classes needed to deserialize
Json data
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.
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;
}