I'm having problems reading Children of the root element and understanding where I'm going wrong in the JSON below:
{
"001": {
"peers": [
{
"id": 0,
"server": "1.1.1.1:80",
"name": "1.1.1.1:80",
"backup": false,
"weight": 1,
"state": "up",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
},
{
"id": 1,
"server": "127.0.0.1:8888",
"name": "127.0.0.1:8888",
"backup": false,
"weight": 1,
"state": "down",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
}
],
"keepalive": 0,
"zombies": 0,
"zone": "001"
},
"002": {
"peers": [
{
"id": 0,
"server": "1.1.1.2:80",
"name": "1.1.1.2:80",
"backup": false,
"weight": 1,
"state": "up",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
},
{
"id": 1,
"server": "127.0.0.1:8888",
"name": "127.0.0.1:8888",
"backup": false,
"weight": 1,
"state": "down",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
}
],
"keepalive": 0,
"zombies": 0,
"zone": "002"
}
}
I know I can pass the JSON into a JObject and find the server value below by naming the 001
JSON object:
JObject obj = JObject.Parse(jsonResponse);
var h = obj.Value<JObject>("001").Value<JArray>("peers")[0].SelectToken("server").ToString();
However I'd like to read the children of the root element (which I think are objects 001
and 002
) regardless of their names, foreach through them to find values for the keys "zone" and "keepalive". I thought I could do this:
List<JToken> toks = obj.Root.Children().ToList<JToken>();
string output = "";
foreach (JToken token in toks)
{
JProperty prop = (JProperty)token;
output += prop.Value<string>("zone"); // returns nothing
string bla = token.ToString(); //returns 001 and all it's child objects
}
But the output string is blank. I can see that if I try token.ToString()
the JToken
object has stuff in it, but I can't seem to read it.
If I use Visual studio to create an object for Deserialization I get this for the root object which confuses me further:
public class Rootobject
{
public 001 001 { get; set; }
public 002 002 { get; set; }
}
What am I doing wrong? Any help would be greatly appreciated.
Jon