我正在使用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)
}