Can't get head around parsing nested JSON

筅森魡賤 提交于 2019-12-25 02:52:07

问题


I am having a hard time trying to get my head around this here:

so I have the following JSON:

"posts": [
{
  "id": 42400,
  "type": "post",
  "url": "http://dummy.com/noticias/2014/06/senado-promulga-emenda-contra-trabalho-escravo-42400/",
  "status": "publish",
  "title": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
  "title_plain": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
  "content": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>",
  "excerpt": "<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>",
  "date": "2014-06-05 16:59:55",
  "modified": "2014-06-05 17:00:42",
  "author": {
    "id": 2,
    "slug": "author",
    "name": "Author",
    "first_name": "Author",
    "last_name": "",
    "nickname": "Author",
    "url": "",
    "description": ""
  },
  "thumbnail_images": {
    "full": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo.jpg",
      "width": 585,
      "height": 390
    },
    "thumbnail": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-110x110.jpg",
      "width": 110,
      "height": 110
    },
    "medium": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-230x130.jpg",
      "width": 230,
      "height": 130
    },
    "large": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-585x360.jpg",
      "width": 585,
      "height": 360
    },
    "slider-thumb": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-520x390.jpg",
      "width": 520,
      "height": 390
    }
  }  
},

And this is how I am parsing this JSON:

NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

if (localError != nil ) {
    *error = localError;
    return nil;
}

NSMutableArray *posts = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:@"posts"];

for (NSDictionary *postDic in results) {

    Data *data = [[Data alloc] init];
    for (NSString *key in postDic) {
        if ([data respondsToSelector:NSSelectorFromString(key)]) {
            [data setValue:[postDic valueForKey:key] forKey:key];
        }
    }

    [posts addObject:data];
}

return posts;

What I can't seem to understand is how can I access the first value inside "thumbnail_images", which is "full" and then get its 'url' value.


回答1:


The JSONObjectWithData method creates an object that consists of nested NSArrays and NSDIctionarys. To extract items of interest you have to drill down into the object, repeatedly extracting arrays and dictionaries until you reach whatever it is that you want. Using the modern syntax for arrays and dictionaries makes this relatively easy.

Also note that the error return is only valid if the return value from JSONObjectWithData is nil.

NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

if ( parsedObject == nil )
{
    *error = localError;
    return nil;
}

NSMutableArray *results = [NSMutableArray new];
NSArray *posts = parsedObject[@"posts"];

for ( NSDictionary *post in posts )
{
    NSDictionary *thumb = post[@"thumbnail_images"];
    NSDictionary *full  = thumb[@"full"];
    NSString *urlString = full[@"url"];
    NSLog( @"%@", urlString );

    [results addObject:urlString];
}

return [results copy];



回答2:


The key "posts" has an NSArray for it's value, which is your variable named results. Each index of the results array can contain an array or dictionary.

thumbnail_images is at index 1, so you can get it like this NSDictionary *thumbImages = results[1];

From here on out, you can access all the nested keys you want like this. So for "full" and then "url": NSString *url = thumbImages[@"thumbnail_images"][@"full"][@"url"];




回答3:


You can check if the object is a dictionary and then traverse through it:

for (NSDictionary *postDic in results) {

Data *data = [[Data alloc] init];
for (NSString *key in postDic) {
    if ([data respondsToSelector:NSSelectorFromString(key)]) {
        if ([results[postDic] isMemberOfClass:[NSDictionary class]) {
            // At this point you will get the "full", "thumbnail", etc dictionaries
            NSDictionary *childDict = results[postDic];
            //Now you can just do the same thing once again to get the url value.
        }
        [data setValue:[postDic valueForKey:key] forKey:key];
    }
}

[posts addObject:data];
}


来源:https://stackoverflow.com/questions/24072891/cant-get-head-around-parsing-nested-json

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