我正在尝试读取json文件并将元素添加到列表中,以便我可以更轻松地调用它们。我无法弄清楚如何将所有“ Heads”值添加到列表中。
所以我可以打电话给
listname[index].key
listname[key].value
返回可以在其中获得示例的东西。(“ Small_Cube_Head”:{“ Colors”:{“ Default”})
我基本上希望能够调用“ Small_Cube_Head”和所有颜色值
JSON文件
{
"Heads":{
"Large_Cube_Head":["Default","e97451"],
"Medium_Cube_Head":["Default","ffffff","76d7ea","e97451","5fa777","f4c430","d0ff14","0047ab","e32636","fc419a","720b98","ff8b00","000000","848482"],
"Small_Cube_Head":["Default"]
}
}
}
代码
/**
* json: Returns the whole file as a String
**/
private void LoadJson()
{
using (StreamReader r = new StreamReader("Assets/JSON/PlayerPartsList.json"))
{
json = r.ReadToEnd();
//Debug.Log(json);
JSONNode node = JSON.Parse(json);
Debug.Log(node["Heads"].Count); //returns 3
for (int i = 0; i < node["Heads"].Count; i++) {
//headParts.Add(node["Heads"].);
//Debug.Log(node["Heads"][i].Value.ToString());
//Debug.Log(node["Heads"]["Small_Cube_Head"].Value);
}
}
}
答案 0 :(得分:1)
像枚举器一样使用Keys
来获取每个标题名称,然后可以循环浏览该headName的计数作为索引
KeyEnumerator headNameEnum = node["Heads"].Keys;
while (headNameEnum.MoveNext())
{
String headName = headNameEnum.Current().Value;
Debug.Log("headName: " + headName);
for (int i=0; i < node["Heads"][headName].Count; i++) {
String valueName = node["Heads"][headName][i].Value;
Debug.Log("valueName: " + valueName);
}
}