解析JSON阵列成的NSDictionary(Parsing a JSON array into a

2019-06-24 01:38发布

我与天气地下API努力使一个应用程序,我一直在分析有关严重的警报块碰钉子。 JSON的使用有子键值对key-value对 - 这还没有给我一个问题,因为我可以让后续的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"
    }
]

“警报”对不同于其他我已经能够解析,因为它周围的子值这个[]支架和我不知道如何清除它,所以我可以访问子值。 在其他的例子,我已经能够解析,它只有在括号{},而不是同时与{}和[]括号中。 作为参考,括号内是始终存在 - 即使没有灾害性天气警报......在该实例的“警报”对返回括号[]与当前没有子对。

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


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

1)从原始JSON创建一个NSDictionary

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

2)创建用于嵌套JSON对随后的字典

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

3)分配的值

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

所以,最终的结果将是一个字符串,说:“晴间多云”什么的,与我没有表现出大量相关的天气值一起。 这些成功的解析,因为他们只拥有范围括号{},而不是括号[]。

Answer 1:

托架装置JSON数据有在阵列中。 你可以解析它如下

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

现在你应该通过所有警报环路和解析它们(在你的情况下,它只有1个,但也可能在其他的JSON字符串会更多):

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


Answer 2:

好吧,我得到它的工作 - 我想在这里提供一个例子,因为我最后不得不建立在@Lefteris了得到它的工作的建议。

我最后不得不先通过JSON阵列作为一个NSArray,然后我转换到这一个NSDictionary与阵列的第一个元素。 后来担任@Lefteris一切描述。

因此,在最后,这里是我得到了什么:

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"];
        ...
    }
} 

这让我起来,用一个单一的阵列迭代运行-怎么回事我希望我可以通过阵列只会重复,因为我知道计数和处理任何额外的警报。 再次感谢您的帮助!



文章来源: Parsing a JSON array into a NSDictionary