我使用LitJSON来加载.json数据,并且我正在使用foreach循环运行一些测试代码,但是它不起作用。
InvalidOperationException: Instance of JsonData is not a dictionary
LitJson.JsonData.EnsureDictionary()(运行foreach行时引发此错误)
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");
}
}根据文档中的示例 (Ctrl+F "foreach";它在页面底部附近),我很确定这段代码应该能工作(?)。
有人知道为什么这行不通吗?我们将非常感谢您的建议!
编辑:解决方案是将数据转换为IList对象,如下所示:
foreach (JsonData i in data as IList) {
Debug.Log("foreach: " + i)
}发布于 2016-05-08 22:22:01
1.不要在任何不在统一中的数组上使用foreach。它无情地分配记忆。
2.Unity有一个内置的Json序列化,名为JsonUtility。我建议你用这个。它目前不支持数组,您的问题表明您正在使用Json数组。有一个解决方案可以让它与数组一起工作。看这里。从2.多个数据(数组JSON)的位置读取。一旦你使它工作,这将是很容易做下一次,不需要外部库。我还推荐它,因为它比大多数其他Json库都快。
注意事项:您需要Unity5.3及更高版本才能使其工作。
编辑:
从我的评论来看,这起作用了
foreach (var i in data as IList){
}https://stackoverflow.com/questions/37105257
复制相似问题