Yogi
Yogi

Reputation: 169

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?

Upvotes: 0

Views: 66

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129807

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.

Upvotes: 1

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30355

I am not quite sure what you want to achieve, but why would you need to know the name of the object as string? Usually you have some structure in JSON and if you know that you always have 2 children "left" and "right", then you can just use jsonData["nodes"]["left"] and jsonData["nodes"]["right"] to get the corresponding objects and continue further down to get the data.

If you can have arbitrary data I would suggest using an array instead with "name": "left", "name": "right".

Even the best approach is to deserialize the string to an ordinary C# class, e.g.:

string value = "your json here"
MyObject obj = JsonConvert.DeserializeObject<MyObject>(value);

MyObject is just a class that mimics the JSON structure. In your case it will have just Nodes property that will be IEnumerable<Node>, where Node will have Left and Right properties and so on.

Upvotes: 0

Related Questions