首页 > 解决方案 > 在 C# 中循环一个 SimpleJSON 数组

问题描述

我有一个从我的 Web 服务器获取 JSON 的 Unity 项目。

[
  {
    name: "foo",
    start: 1,
  },
  {
    name: "bar",
    start: 5,
  },
  {
    name: "baz",
    start: 10,
  },
]

我正在使用SimpleJSON解析 JSON 字符串

  var res = JSON.Parse(www.downloadHandler.text);

访问单个数组元素没有问题。

Debug.Log(res[0]["name"].Value);
// logs "foo"

Debug.Log(res[1]["start"].AsInt);
// logs 5

但我不知道如何遍历每个对象并访问其属性。(我的真实数据在数组中有超过 3 个对象)。

   foreach (var item in res) {
        string name = item["name"].Value;
   }

给出错误:

CS0021:无法使用 [] 将索引应用于“KeyValuePair<string, JSONNode>”类型的表达式

这在 javascript 中是微不足道的,为什么在 C# 中这么难?我被困了一整天,我确定我错过了一些简单的东西。

标签: c#arraysjsonunity3dsimplejson

解决方案


尝试这个

for (int i = 0; i< res.Count; i++)  //or res.Count()
{ 
   var name res[i]["name"].Value;
....your code
}

你也可以使用它:

foreach( KeyValuePair<string, JSONNode> entry in res)
{
    // do something with entry.Value or entry.Key
}

但第一种方法更简单。


推荐阅读