Parsing a JSON array into a NSDictionary

旧时模样 提交于 2019-11-29 02:02:26

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

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):

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

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.

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.

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!