我在服务器中有一个这样的json,我想获取“ challenge_id”和“渲染的”数据:
我尝试像这样通过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);
}
}
但是当我玩游戏时,控制台会显示所有“已渲染”和“ challenge_id”数据以及许多其他带有“ null”的条目。
“ Prueba 2 Piratas挑战” UnityEngine.Debug:Log(对象) “ 5c2c8da810dd2304e3d3bcd9” UnityEngine.Debug:Log(对象) “普鲁巴挑战皮拉塔斯” UnityEngine.Debug:Log(对象) “ 5c24cfa46315fb04ff78c02c” UnityEngine.Debug:Log(对象) “杨桃” UnityEngine.Debug:Log(对象) “ 5c24cacd6315fb04ff6fce22” UnityEngine.Debug:Log(对象) 空值 UnityEngine.Debug:Log(对象) 空值 UnityEngine.Debug:Log(对象) 空值 UnityEngine.Debug:Log(对象) 空值 UnityEngine.Debug:Log(对象) 空值 UnityEngine.Debug:Log(Object)
我在做什么错?预先感谢!
答案 0 :(得分:3)
您正在迭代
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]
时,如果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
。