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

时间:2013-02-27 00:56:01

标签: iphone ios xcode json

我正在用JSON解析一个itunes rss feed但是我遇到了一个问题。以下代码正在为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 
}

以下是我正在解析的链接:http://itunes.apple.com/us/rss/topmovies/limit=300/json

2 个答案:

答案 0 :(得分:0)

问题在于,当我将字符串添加到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];
}

答案 1 :(得分:0)

我经常遇到这种情况。我用的是这样的东西。替换您的代码

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

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

其中-ifNullThenNil通过类别提供:

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

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