Search code examples
c#unity-game-engineforeachlitjson

LitJSON: Unable to use foreach in Unity


I'm using LitJSON to load .json data, and I'm running some test code with a foreach loop, but it's not working.

InvalidOperationException: Instance of JsonData is not a dictionary
LitJson.JsonData.EnsureDictionary()

(this error is thrown when the foreach line is run)

    using UnityEngine;
    using LitJson;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;

    public void LoadData() {
        JsonReader reader = new JsonReader("[1, 2, 3, 4, 5]");
        JsonData data = JsonMapper.ToObject(reader);

        foreach (JsonData i in data) {
          Debug.Log("foreach: test");
        }
    }

According to the example in the documentation (Ctrl+F "foreach"; it's near the bottom of the page), I'm pretty sure this code should work (?).

Anyone have any ideas as to why this wouldn't work? Advice would be greatly appreciated!

Edit: The solution is to cast data to an IList object as follows:

foreach (JsonData i in data as IList) {
    Debug.Log("foreach: " + i)
}

Solution

  • 1.Don't use foreach on anything that is not array in Unity. It allocates memory mercilessly.

    2.Unity has a Built in Json serialize called JsonUtility. I suggest you use that. It currently does not support array and your question suggests you are using Json array. There is a solution to get it work with array. Look here. Read from where it says 2. MULTIPLE DATA(ARRAY JSON). Once you get it working, it will be easy to do next time and no external library required. I also recommend it because it faster than most other Json libraries.

    Note: You need Unity 5.3 and above to get this to work.

    EDIT:

    From my comment, this worked

    foreach (var i in data as IList){
    
    }