Ant*_*ace 10 json objective-c nsdictionary ios5
我正在使用Weather 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"
}
]
Run Code Online (Sandbox Code Playgroud)
"警报"对与我能够解析的其他对不同,因为它有围绕子值的这个[]括号,我不知道如何清除它以便我可以访问子值.在我能够解析的其他示例中,它只有{}括号,而不是{}和[]括号.作为参考,括号始终存在 - 即使没有恶劣天气警报......在该情况下,"警报"对返回没有子对的括号[].
有没有办法可以从NSDictionary中删除[]括号,或者忽略它们?任何意见,将不胜感激!
有关参考和故障排除帮助,以下是我如何成功解析其余的JSON文档:
1)从原始JSON创建NSDictionary
//Process Weather Call
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Run Code Online (Sandbox Code Playgroud)
2)为嵌套的json对创建后续字典
NSDictionary *current_observation = [json objectForKey:@"current_observation"];
Run Code Online (Sandbox Code Playgroud)
3)分配值
NSString* weather;
weather = [current_observation objectForKey:@"weather"];
Run Code Online (Sandbox Code Playgroud)
因此,最终结果将是一个字符串,表示"部分多云"或其他东西,以及我没有显示的许多相关天气值.这些解析成功,因为它们只有范围括号{},而不是[]括号.
Lef*_*ris 19
括号表示数组中的Json数据.您可以按如下方式解析它
NSArray *alertArray = [json objectForKey:@"alerts"];
Run Code Online (Sandbox Code Playgroud)
现在你应该循环遍历所有警报并解析它们(在你的情况下它只有1,但它可能在另一个json字符串中更多):
//parse each alert
for (NSDictionary *alert in alertArray ){
NSString* description = [alert objectForKey:@"description"];
//etc...
}
Run Code Online (Sandbox Code Playgroud)
好吧,我得到了它的工作 - 我想在这里提供一个例子,因为我最终必须建立@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"];
...
}
}
Run Code Online (Sandbox Code Playgroud)
这让我开始运行单个数组迭代 - 继续我希望我可以简单地遍历数组,因为我知道计数并处理任何其他警报.再次感谢您的帮助!
归档时间: |
|
查看次数: |
22751 次 |
最近记录: |