将 JSON 数组解析为 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10368303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:18:29  来源:igfitidea点击:

Parsing a JSON array into a NSDictionary

objective-cjsonios5nsdictionary

提问by Anthony Neace

I'm working with the Weather Underground API to make an app and I've hit a snag while parsing the block relating to severe alerts. The JSON uses key-value pairs that have sub key value pairs -- which haven't been a problem for me, as I can make subsequent NSDictionaries out of those -- but the entry for severe alerts has proven problematic. See below:

我正在使用 Wea​​ther Underground API 制作一个应用程序,但在解析与严重警报相关的块时遇到了障碍。JSON 使用具有子键值对的键值对——这对我来说不是问题,因为我可以从中制作后续的 NSDictionaries——但是严重警报的条目已被证明是有问题的。见下文:

"alerts": [
    {
    "type": "WAT",
    "description": "Flash Flood Watch",
    "date": "3:13 PM EDT on April 28, 2012",
    "date_epoch": "1335640380",
    "expires": "8:00 AM EDT on April 29, 2012",
    "expires_epoch": "1335700800",
    "message": "\u000A...Flash Flood Watch in effect through Sunday morning...\u000A\u000AThe National Weather Service in Charleston has issued a\u000A\u000A* Flash Flood Watch for portions of northeast Kentucky... (Note: I trimmed this for length's sake),
    "phenomena": "FF",
    "significance": "A"
    }
]

The "alerts" pair differs from others I've been able to parse because it has this [ ] bracketsurrounding the sub-values and I'm not sure how to clear it so I can access the subvalues. In the other examples I've been able to parse, it only has the { } brackets, and not both the { } and [ ] brackets. For reference, the brackets are always present -- even when there are no severe weather alerts... in that instance the "alerts" pair returns the brackets [ ] with no sub-pairs present.

“警报”对与我能够解析的其他对不同,因为它在子值周围有这个[] 括号,我不知道如何清除它以便我可以访问子值。在我能够解析的其他示例中,它只有{ } 括号,而不是 { } 和 [ ] 括号。作为参考,括号始终存在——即使没有恶劣天气警报......在这种情况下,“警报”对返回括号 [],不存在子对。

Is there a way I can remove the [ ] brackets from the NSDictionary, or otherwise ignore them? Any advice would be appreciated!

有没有办法可以从 NSDictionary 中删除 [] 括号,或者以其他方式忽略它们?任何意见,将不胜感激!



For reference and troubleshooting help, here's how I'm parsing the rest of the JSON document successfully:

作为参考和故障排除帮助,以下是我如何成功解析 JSON 文档的其余部分:

1) Create an NSDictionary from the raw JSON

1) 从原始 JSON 创建一个 NSDictionary

//Process Weather Call
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

2) Create subsequent dictionaries for nested json pairs

2)为嵌套的json对创建后续字典

NSDictionary *current_observation = [json objectForKey:@"current_observation"];

3) Assign values

3) 赋值

NSString* weather;
weather = [current_observation objectForKey:@"weather"];

So the end result would be a string that says "Partly Cloudy" or something, along with numerous related weather values that I haven't shown. These parse successfully because they only have the scope brackets { }, and not the [ ] brackets.

所以最终结果将是一个字符串,上面写着“部分多云”之类的东西,以及许多我没有显示的相关天气值。这些解析成功是因为它们只有范围括号 {},而不是 [] 括号。

回答by Lefteris

The brackets means the Json data there are in an array. You can parse it as following

括号表示数组中的 Json 数据。您可以将其解析如下

NSArray *alertArray = [json objectForKey:@"alerts"];

now you should loop through all alerts and parse them (in your case it's only 1, but it could be more in another json string):

现在您应该遍历所有警报并解析它们(在您的情况下它只有 1 个,但在另一个 json 字符串中可能更多):

//parse each alert
for (NSDictionary *alert in alertArray ){
     NSString* description = [alert  objectForKey:@"description"];
    //etc...
}

回答by Anthony Neace

Okay, I got it working -- and I wanted to provide an example here because I ended up having to build on the advice @Lefteris gave to get it working.

好的,我让它工作了——我想在这里提供一个例子,因为我最终不得不根据@Lefteris 给出的建议来让它工作。

I ended up having to pass the json array first as an NSArray, and then I converted that into an NSDictionary with the first element of the array. Everything afterwards worked as @Lefteris described.

我最终不得不首先将 json 数组作为 NSArray 传递,然后我将其转换为包含数组第一个元素的 NSDictionary。之后的一切都按照@Lefteris 的描述进行。

So, in the end, here's what I've got:

所以,最后,这就是我所得到的:

NSArray *alerts = [json objectForKey:@"alerts"];
NSDictionary *alertDict = [[NSDictionary alloc] init];

//Check that no alerts exist to prevent crashing
if([alerts count] < 1) {
    NSLog(@"No Alerts Here!");
    type = nil;
    ...
}
else  //Populate fields
{
    alertDict = [alerts objectAtIndex:0];
    for (NSDictionary *alert in alertDict)
    {
        NSLog(@"Printing alert!");
        type = [alertDict objectForKey:@"type"];
        ...
    }
} 

This got me up and running with a single array iterate-- going on I expect I can simply iterate through the array since I know the count and handle any additional alerts. Thanks again for the help!

这让我启动并运行了单个数组迭代- 继续我希望我可以简单地遍历数组,因为我知道计数并处理任何其他警报。再次感谢您的帮助!