1

最初に確認しようとしても、一部の json が null の場合、次のコードでエラーが発生します。

編集:前のコード:

NSData* data = [NSData dataWithContentsOfURL: kItemsURL];
            //previous line grabed data from api.
            if (data) {
                [self performSelectorOnMainThread:@selector(fetchData:) withObject:data waitUntilDone:YES];
}
- (void)fetchData:(NSData *)jsonFeed {
     NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonFeed                                                           options:kNilOptions                                                             error:&error];

//Original code provided
    if (![[json objectForKey:@"items"] isKindOfClass:[NSNull class]]) {
            NSLog(@"got here");
            NSLog(@"json%@",json);
            latestItems = [[json objectForKey:@"items"]mutableCopy];
    }

Jsonがnullでないことを確認するより良い方法はありますか?

エラー出力は次のとおりです。

2016-05-03 13:05:43.820 testApp[407:60b] got here
2016-05-03 13:05:43.821 testApp[407:60b] json{
    items = "<null>";
}
NSNull mutableCopyWithZone:]: unrecognized selector sent to instance 0x3ac26a70
2016-05-03 13:05:43.825 ChallengeU[407:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull mutableCopyWithZone:]: unrecognized selector sent to instance 0x3ac26a70'  
4

4 に答える 4

0
if (![json[@"items"] isEqual:[NSNull null]]) {
//do your stuff in here

}
于 2016-05-03T21:10:36.303 に答える
0

コードの何が問題なのかはわかりませんが、json が辞書であることが確実な場合に JSON の null 値を確認する最も簡単な方法は次のとおりです。

if (json [@"items"] != [NSNull null]) { ... }

[NSNull null]は、常にNSNullの同じインスタンスを返します。NSNull のインスタンスは 1 つしか存在しないため、実際にポインター比較を使用して、オブジェクトが NSNull インスタンスであるかどうかを確認できます。

于 2016-05-03T22:52:36.923 に答える
-1
if (json && [json isKindOfClass:[NSDictionary class]]) {
    //your code here
} else {
    //invalid json
}
于 2016-05-04T03:42:50.733 に答える