【问题标题】:Many null entries when parse a json解析 json 时出现许多空条目
【发布时间】:2019-01-11 19:50:15
【问题描述】:

我在服务器中有一个这样的 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 挑战” UnityEngine.Debug:日志(对象) “5c2c8da810dd2304e3d3bcd9” UnityEngine.Debug:日志(对象) “普鲁巴挑战海盗” UnityEngine.Debug:日志(对象) “5c24cfa46315fb04ff78c02c” UnityEngine.Debug:日志(对象) “普鲁巴杨桃” UnityEngine.Debug:日志(对象) “5c24cacd6315fb04ff6fce22” UnityEngine.Debug:日志(对象) 空值 UnityEngine.Debug:日志(对象) 空值 UnityEngine.Debug:日志(对象) 空值 UnityEngine.Debug:日志(对象) 空值 UnityEngine.Debug:日志(对象) 空值 UnityEngine.Debug:Log(Object)

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

【问题讨论】:

  • 你能用实际的文本替换文本的图像吗?这使得有类似问题的人更容易找到这个问题。它还使问题更易于阅读、讨论和回答,尤其是对于使用屏幕阅读器的人。无论如何,你为什么要循环到i &lt; jsonString.Lengthi &lt; N.Count 不是更有意义吗?
  • 我个人建议使用 NewtonSoft 来处理您的 JSON。这是您可以获得的 Nuget 包。它非常容易处理反序列化和序列化。

标签: c# json unity3d


【解决方案1】:

你正在迭代

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 =&gt; 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

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2018-04-25
    • 1970-01-01
    • 2019-05-24
    • 2018-08-11
    • 2018-08-24
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多