c# - 在 C# 中循环一个 SimpleJSON 数组
问题描述
我有一个从我的 Web 服务器获取 JSON 的 Unity 项目。
[
{
name: "foo",
start: 1,
},
{
name: "bar",
start: 5,
},
{
name: "baz",
start: 10,
},
]
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# 中这么难?我被困了一整天,我确定我错过了一些简单的东西。
解决方案
尝试这个
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
}
但第一种方法更简单。
推荐阅读
- scala - 从 `=> T` 到 `() => T` 再返回
- python - 在 tkinter 中使滚动条更长
- python - 用 Pandas & xlrd 读取 XLS 文件返回错误;xlrd 自行打开文件
- aws-api-gateway - 我正在尝试访问 VPC 内的 AWS API 网关,但不断收到超时错误
- swift - 如何在 swiftUI 中管理按钮状态
- excel - 为什么if语句中变量中的数组值不相等?
- flutter - 缩放/缩小小部件并保持字体大小成比例
- kubernetes - Istio-在路由前检查另一台主机
- r - 将 scale_shape_manual 制作的图例与命名向量相结合
- git - 如何取回未提交的文件?