ios - 在 Objective C 中使用键名作为递增整数解析 JSON

标签 ios objective-c json

不太确定如何表达这个问题,但我有一些 JSON 需要解析,格式如下:-

"nodes": {
    "4": {
        "node_id": 4,
        "title": "TITLE 1",
        "description": "",
    },
    "7": {
        "node_id": 7,
        "title": "TITLE 2",
        "description": "",
    },
    "12": {
        "node_id": 12,
        "title": "TITLE 3",
        "description": "",
    },

通常我会使用标准 [dictionary objectForKey@"key"] 来获取值,但是当项目以整数(字符串)开头时,我发现很难正确解析。我在这里错过了一些非常简单的东西吗?

最佳答案

如果您只想访问一个值,则可以执行以下操作。

// Assume JSONObject is the "root" dictionary
NSDictionary *fourDictionary = JSONObject[@"nodes"]["4"] // This will get the object from "4":{}

现在,如果所讨论的 JSON 可以具有动态数量的对象,那么这就更加棘手了。最简单的解决方案是让 JSON 的提供者将其重写为对象数组。您可以使用对象的 node_id 值查找您想要的对象。

如果这不可能,那么您可以尝试编写一个 for 循环来遍历“节点”对象中的所有键并以这种方式访问​​字典中的项目。

NSMutableArray *arrayOfNodes = [NSMutableArray array];
NSDictionary *nodes = JSONObject[@"nodes"];
for(NSString *numberKey in [nodes allKeys])
{
    NSDictionary *nodeObject = nodes[numberKey]
    [arrayOfNodes addObject:nodeObject];
}
// Do anything else with the nodes now that they are in an array. 

关于ios - 在 Objective C 中使用键名作为递增整数解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30224303/

相关文章:

ios - 如何布局可以有无限多行的UILabel

ios - 在 iOS 上获取当前位置

json - D3.js 的最大数据文件大小

java - Gson:读取/src文件夹中的json文件并将对象附加到其中

mysql - 如果子查询在 MySQL 中返回多于 1 行,如何将 JSON 放入列数据中

android - 在IOS中将android DP转换为Points

ios - 使用 UIProgressView 将进度条设置为 30 分钟

javascript - 修改WKWebView中不存在的DOM元素

ios - 上下滚动时 UISwitch 重置

ios - 可以拖动到 View Controller 中任何位置的 float 按钮?