JSON in .NET C#/Csharp - Getting values out of the object
I want to parse some JSON data. I'm using James Newton-King's JSON.NET library.
I parse the JSON string into a JObject. Here is the JSON I'm parsing:
"root": [
{
"date": 1325400000000,
"id": 12313131,
"loc": "en_us",
"name": "New York, NY",
"products": [
{
"@type": "asdf",
"city": "New York - Penn Station, NY (NYP)",
"code": "USA",
}
],
"summary": {
"alert": [],
"end": 1325577000000,
"start": 1325400000000
}
}
]
}
As you can see it's pretty complex. The "root" was necessary because otherwhise the data could not be parsed into a JObject instance.
JObject o = JObject.Parse(jsonString);
The JSON data is quite large. There are multiple items in it with different IDs. I want to find an item with a specifid ID.
The problem is, when I try to foreach through the data it has only one element.
KEY: root
VALUE: the 开发者_Go百科other stuff.
So how do I get to the other stuff and cycle through what's inside?
Nevermind..
I just solved it.
I removed the trailing [ and the end ].
So it is now a Valid Json object and Key Value foreach is working like a charm..
foreach (KeyValuePair<String, JToken> d in o)
{
Console.WriteLine(String.Format("Key: {0}; Value: {1}", d.Key, d.Value));
}
Hurray!
Turned out this is only a partial solution. Because now the others are not formatted only the first segment is. The others somehow disappear... :S Damn this...
Even better solution... I was a complete idiot...
Leave everything in place and simply use JArray ja = JArray.Parse(stringOfJson);
This will give you an array full with all the data free to cycle through... Awesome. :)
精彩评论