简体   繁体   English

如何解析JSON并拥有2个最终数据数组

[英]How to parse JSON and have 2 final arrays of data

I am parsing an itunes rss feed with JSON but I have run into a problem. 我正在使用JSON解析itunes rss feed,但是遇到了问题。 The following code is running properly for one the movieName output but I still don't get the movieSummary output. 以下代码对于movieName输出之一正常运行,但是我仍未获得movieSummary输出。

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
    feed = [allDataDictionary objectForKey:@"feed"];
    arrayOfEntry = [feed objectForKey:@"entry"];

    for (NSDictionary *dictionTitle in arrayOfEntry) {

        NSDictionary *title = [dictionTitle objectForKey:@"title"];
        NSString *labelTitle = [title objectForKey:@"label"];

        [arrayLable addObject:labelTitle];

        NSDictionary *summary = [dictionTitle objectForKey:@"summary"];
        NSString *labelSummary = [summary objectForKey:@"label"];

        [arraySummary addObject:labelSummary];
    }

    movieName.text = [arrayLable objectAtIndex:0];
    movieSummary.text = [arraySummary objectAtIndex:0]; //This is not displaying 
}

Here is the link that I am parsing: http://itunes.apple.com/us/rss/topmovies/limit=300/json 这是我正在解析的链接: http : //itunes.apple.com/us/rss/topmovies/limit=300/json

The problem was that when I was adding the strings to the Array that it sometimes contained NULL's thus the following code helped me out 问题是当我将字符串添加到Array时,它有时包含NULL,因此以下代码帮助了我

    if ([[arrayName objectAtIndex:0] isKindOfClass:[NSNull class]]) {
    labelName.text = @"This is NULL";
} else {
    [arrayName addObject:labelName];
}

    if ([[arraySummary objectAtIndex:0] isKindOfClass:[NSNull class]]) {
    labelSummary.text = @"This is NULL";
} else {
    [arraySummary addObject:labelSummary];
}

I run into this situation a lot. 我经常遇到这种情况。 I use something like this. 我用这样的东西。 Replace your code 替换您的代码

NSString *labelTitle = [title objectForKey:@"label"];
[arrayLable addObject:labelTitle];

with

NSString * labelTitle = [ [ title objectForKey:@"label" ] ifNullThenNil ] ;
[ arrayLabel addObject:labelTitle ? labelTitle : @"" ] ; // you could also use @"<unknown>" or similar instead of @""

where -ifNullThenNil is provided via category: 其中-ifNullThenNil通过类别提供:

@implementation NSObject (IfNullThenNil)
-(id)ifNullThenNil { return self ; }
@end

@implementation NSNull (IfNullThenNil)
-(id)ifNullThenNil { return nil ; }
@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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