首页 > 解决方案 > 使用 SimpleJSON C# 帮助获取信息

问题描述

我正在尝试读取 json 文件并将元素添加到列表中,以便我可以更轻松地调用它们。我无法弄清楚如何将所有“Heads”值添加到列表中。

所以我可以打电话

listname[index].key
listname[key].value

返回一些我可以获得示例的东西。(“Small_Cube_Head”:{“Colors”:{“Default”})

我基本上希望能够调用“Small_Cube_Head”和所有颜色值

文件

{
"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);

        }
    }
    }

标签: c#jsonsimplejson

解决方案


像枚举器一样使用Keys来获取每个头部名称,然后您可以循环遍历该头部名称的计数作为索引

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);
    }

}

推荐阅读