Yogi Yogi - 1 month ago 15
JSON Question

Simple Json.NET task but totally confused

I've been figuring out ways to use json.net and I have the following simple test case.

JObject jsonData = JObject.Parse("{\"nodes\": { \"left\": {\"att\": 1.0, \"ch\": 0}, \"right\": {\"att\": 1.0, \"ch\": 1}}}");

var nodes = jsonData ["nodes"].Children ();

foreach (JToken node in nodes) {
JToken speaker = node.First;
float attenuation = (float)speaker ["att"];
int channel = (int)speaker ["ch"];
string nodeName = /* HOW TO GET THE OBJECT NAME HERE ("left","right" in this example json) */
}


As I am iterating over the objects, I haven't been able to figure out how could I access the object name in this json (left/right in this example).

Is my parsing strategy totally off or am I missing something obvious?

Answer

Since jsonData["nodes"] here is a JObject, then jsonData["nodes"].Children() is an enumerable containing the JProperties. Each JProperty has a Name and a Value. You just need to cast the JToken back to JProperty (or JObject) as appropriate.

Change your foreach loop to this:

foreach (JProperty node in nodes)
{
    string nodeName = node.Name;
    JObject speaker = (JObject)node.Value;
    float attenuation = (float)speaker["att"];
    int channel = (int)speaker["ch"];
}

By the way, if you have a JToken and you don't know what type it is, (e.g. JProperty, JObject, JArray, etc.) you can look at the Type property on the JToken.

If your ultimate goal is merely to convert the JSON to regular dictionaries and lists, you might find this answer helpful.