gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:01:09 27 4
gpt4 key购买 nike

不太确定如何表达这个问题,但我有一些 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com