简体   繁体   中英

iOS Parse Inner Json

Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!

JSON

{"nodes":[{
    "node":{
        "nid":"1420857",
        "title":"Title 1",
        "votes":"182",
        "popular":"True",
        "teaser":"Teaser 1"
    }},
    {"node":{
        "nid":"1186152",
        "title":"Title 2",
        "votes":"140",
        "popular":"True",
        "teaser":"Teaser 2"
    }},
    {"node":{
        "nid":"299856",
        "title":"Title 3",
        "votes":"136",
        "popular":"True",
        "teaser":"Teaser 3"
    }}
]}

Json Parser

    NSError *error = nil;
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.somefilename.json"]];
    if (jsonData) {
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"error is %@", [error localizedDescription]);
            return;
        }
        NSArray *keys = [jsonObjects allKeys];
        for (NSString *key in keys) {
            NSLog(@"%@", [jsonObjects objectForKey:key]);
        }
    } else {
        // Handle Error
    }

Just typecast it:

NSArray *nodes = (NSArray*)[jsonObjects objectForKey:@"nodes"];
for (NSDictionary *node in nodes){
     // do stuff...
}

Methods that return id (like -[objectForKey:] , and -[objectAtIndex:] ) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:

  • object -> NSDictionary
  • array -> NSArray
  • string -> NSString
  • number -> NSNumber
  • boolean -> NSNumber
  • float -> NSNumber
  • null -> NSNull

To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue] , -[boolValue] , -[floatValue] . Check out the NSNumber docs for more info.

You can use my method for json parsing,

Parse Method:

    -(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
    if (key==nil && content ==nil) {
        completionHandler(nil,nil);
    }
    if ([content isKindOfClass:[NSArray class]]) {
        for (NSDictionary *obj in content) {
          [self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
        }
    }
    if ([content isKindOfClass:[NSDictionary class]]) {
        id result = [content objectForKey:key];
        if ([result isKindOfClass:[NSNull class]] || result == nil) {
            NSDictionary *temp = (NSDictionary *)content;
            NSArray *keys = [temp allKeys];
            for (NSString *ikey in keys) {
             [self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
            }
        }else{
            completionHandler(result,content);
        }
    }
}

Method Call:

 NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Sample" ofType:@"json"]];
    NSError *error;

//to get serialized json data...

   id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];

//get data for key called GetInfo

     [self jsonDeserialize:@"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
            NSLog(@"%@ - %@",parsedData,fromDict);
        }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM