Search code examples
c#arraysjsonunity-game-enginesimplejson

Loop over a SimpleJSON array in C#


I have a Unity project that fetches JSON from a my web server.

[
  {
    name: "foo",
    start: 1,
  },
  {
    name: "bar",
    start: 5,
  },
  {
    name: "baz",
    start: 10,
  },
]

I'm parsing the JSON string with SimpleJSON

  var res = JSON.Parse(www.downloadHandler.text);

I have no problem accessing individual array elements.

Debug.Log(res[0]["name"].Value);
// logs "foo"

Debug.Log(res[1]["start"].AsInt);
// logs 5

But I can't figure out how to loop over each object and access its properties. (my real data has more than 3 objects in the array).

   foreach (var item in res) {
        string name = item["name"].Value;
   }

Gives the error:

CS0021: Cannot apply indexing with [] to an expression of type 'KeyValuePair<string, JSONNode>'

It would be trivial in javascript, why is this so hard in C#? I've been stuck for a whole day, I'm sure I'm missing something simple.


Solution

  • try this

    for (int i = 0; i< res.Count; i++)  //or res.Count()
    { 
       var name res[i]["name"].Value;
    ....your code
    }
    

    you can use this too:

    foreach( KeyValuePair<string, JSONNode> entry in res)
    {
        // do something with entry.Value or entry.Key
    }
    

    but the first way is more simple.