c# - 解析 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)
我究竟做错了什么?提前致谢 !
解决方案
你正在迭代
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
如果索引超出范围,它们只会返回。
推荐阅读
- json - 使用 jq 提取对 shell 变量的 json 响应
- javascript - 等待promise解决并在它执行时做其他事情
- registration - 注册前的 Buddypress 预加载页面
- cordova - Cordova cordova-plugin-googleplus 增量范围
- mysql - 我的测试通过但没有正常结束
- c++ - 方法的静态函数等价
- python - 我的 TensorFlow 应用程序出现错误,我似乎找不到它
- javascript - 将分页调用的结果与 CoinMarketCap API v2 相结合
- docker - 无法使用 docker-compose 构建和运行 docker 容器
- ruby-on-rails - 扩展 ActiveStorage::Attachment - 添加自定义字段