我正在使用fastJSON从我制作的 JSON 文件中读取数据(JSON 文件包含 Unity 项目的游戏关卡数据,但这并不重要)。这是 JSON 内容:
{"1": {
"background": "background1.png",
"description": "A description of this level",
"enemies":
[{"name": "enemy1", "number": "5"},
{"name": "enemy2", "number": "2"}]},
"2": {
"background": "background1.png",
"description": "A description of this level",
"enemies":
[{"name": "enemy1", "number": "8"},
{"name": "enemy2", "number": "3"}]},
"3": {
"background": "background2.png",
"description": "A description of this level",
"enemies":
[{"name": "enemy2", "number": "5"},
{"name": "enemy3", "number": "3"},
{"name": "enemy4", "number": "1"}]}
}
这是我的代码:
using UnityEngine;
using System.Collections.Generic;
using fastJSON;
public class LevelManager : MonoBehaviour {
private Dictionary<string, object> currentLevelData;
public TextAsset levelJSON;
public int currentLevel;
// Use this for initialization
void Start () {
currentLevelData = LevelElements (currentLevel);
if (currentLevelData != null) {
Debug.Log (currentLevelData["background"]);
Debug.Log (currentLevelData["description"]);
/* How iterate the "enemies" array */
} else {
Debug.Log ("Could not find level '" + currentLevel + "' data");
}
}
Dictionary<string, object> LevelElements (int level) {
string jsonText = levelJSON.ToString();
Dictionary<string, object> dictionary = fastJSON.JSON.Parse(jsonText) as Dictionary<string, object>;
Dictionary<string, object> levelData = null;
if (dictionary.ContainsKey (level.ToString ())) {
levelData = dictionary [level.ToString ()] as Dictionary<string, object>;
}
return levelData;
}
}
我不知道如何用名称“敌人”迭代数组数据。