Reputation: 43
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
Upvotes: 3
Views: 250
Reputation: 752
Look at this piece of code
#region Model For Deserialize String to Object
public class Links
{
}
public class List
{
public List<string> staff { get; set; }
public List<string> clients { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public int count { get; set; }
public List list { get; set; }
}
#endregion
#region Restfull Respone (String) Convert To RootObject
public class ConvertStringToObj
{
public void Execute()
{
//Your webReq and Response progress here
string jsonResponse="";
var rootObj = (RootObject)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResponse, typeof(RootObject));
foreach(var eachItem in rootObj.list.staff)
{
var stafName = eachItem;
}
}
}
#endregion
Here is an solution, you can do this via Objects :)
Upvotes: 0
Reputation: 28573
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);
}
Upvotes: 4