首页 > 解决方案 > 解析 json 时出现许多空条目

问题描述

我在服务器中有一个这样的 json,我想获取“challenge_id”和“rendered”数据:

在此处输入图像描述

我尝试像这样使用 SimpleJson 反序列化它:

void Start()
{
    string url = "https://xxxxxxxxxxxxxxxxxxxxxxx";

    WWW www = new WWW(url);
    StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
    yield return www;
    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
        string jsonString = www.text;
        var N = JSON.Parse(jsonString);

        if (name == null)
        {
            Debug.Log("No data converted");
        }
        else
        {
            Debug.Log(N[1]["title"]["rendered"]);
            Debug.Log(N[1]["acf"]["challenge_id"]);

            for (int i = 0; i < jsonString.Length; i++)
            {
                Debug.Log(N[i]["title"]["rendered"]);
                Debug.Log(N[i]["acf"]["challenge_id"]);
            }
        }
    }
    else
    {
        Debug.Log("WWW Error: " + www.error);
    }
}

但是当我玩游戏时,控制台会显示所有“rendered”和“challenge_id”数据以及许多其他带有“null”的条目。

“Prueba 2 Piratas Challenges”UnityEngine.Debug:Log(Object)“5c2c8da810dd2304e3d3bcd9”UnityEngine.Debug:Log(Object)“Prueba Challenge Piratas”UnityEngine.Debug:Log(Object)“5c24cfa46315fb04ff78c02c”UnityEngine.Debug:Log(Object) prueba carambola" UnityEngine.Debug:Log(Object) "5c24cacd6315fb04ff6fce22" UnityEngine.Debug:Log(Object) null UnityEngine.Debug:Log(Object) null UnityEngine.Debug:Log(Object) null UnityEngine.Debug:Log(Object) null UnityEngine.Debug:Log(Object) null UnityEngine.Debug:Log(Object)

我究竟做错了什么?提前致谢 !

标签: c#jsonunity3d

解决方案


你正在迭代

for (int i = 0; i < jsonString.Length; i++)
{
    Debug.Log(N[i]["title"]["rendered"]);
    Debug.Log(N[i]["acf"]["challenge_id"]);
}

所以这个块运行时间......这意味着原始中的jsonString.Length每个字符jsonString

N它不会在您要循环的集合的长度上进行迭代。


所以改为使用

for (int i = 0; i < N.Count; i++)
{
    Debug.Log(N[i]["title"]["rendered"]);
    Debug.Log(N[i]["acf"]["challenge_id"]);
}

或避免任何此类错误

foreach(var n in N)
{
    Debug.Log(n["title"]["rendered"]);
    Debug.Log(n["acf"]["challenge_id"]);
}

但是,我实际上希望您在尝试访问N[i]if i => N.Length... 时得到一个 IndexOutOfRangeException ,但也许这在SimpleJSON中的处理方式不同。

更新

我发现那里的JSONObject类有以下实现:

public override JSONNode this[int aIndex]
{
    get
    {
        if (aIndex < 0 || aIndex >= m_Dict.Count)
            return null;
        return m_Dict.ElementAt(aIndex).Value;
    }
    set
    {
        //...
    }
}

如您所见,null如果索引超出范围,它们只会返回。


推荐阅读