Parsing a JSON array into a NSDictionary

前端 未结 2 1884
暖寄归人
暖寄归人 2020-12-16 03:04

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

相关标签:
2条回答
  • 2020-12-16 03:20

    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!

    0 讨论(0)
  • 2020-12-16 03:40

    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...
    }
    
    0 讨论(0)
提交回复
热议问题