Steven Kiberton Steven Kiberton - 9 months ago 37
JSON Question

C# and jSON is not working

Need a little help here

So I have a json url and need to get each item into a for each loop

Here is the json

{
"_links": { },
"count": 9,
"list": {
"staff": [
"staff1",
"staff2",
"staff3"
],
"clients": [
"client1",
"client2",
"client3",
"client4",
"client5",
"client6"
]
}
}


I have also got the following code in c# but keep getting errors

string source;
var sURL = "LINK_TO_JSON_URL";
WebRequest req = HttpWebRequest.Create(sURL);
req.Method = "GET";
req.Timeout = 5000;
try
{
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
reader.Close();
}
JToken jObject = JObject.Parse(source);
string clients = (string)jObject["list"]["clients"];

//for each loop here

}
catch (Exception ex)
{
//error message here
}


What is it that I am doing wrong? I have tried to convert string to array and still get nothing.
I want to be able to get each clients names

Cheers

Answer Source

So here is some code to show iterating over a JArray that contains strings. This code has been tested with your json and outputs each client string.

var jObject = JObject.Parse(source);

foreach (var client in jObject["list"]["clients"])
{
    Console.WriteLine((string)client);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download