NSJSONSerialization解析错误 - 无法识别的选择器

时间:2014-04-22 05:55:24

标签: ios cocoa-touch nsjsonserialization unrecognized-selector

这是代码:

NSString *jsonString = @"[
            {\"sn\": \"E\", \"t\": \"K\", \"d\": \"Tue 3-Mar\"}, 
            {\"sn\": \"F\", \"t\": \"Y 1\", \"d\": \"Tue 3-Mar\"}
         ]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"jsArray: %@", jsArray);

for (id job in jsArray) {
    NSLog(@"job: %@", job);
    NSLog(@"%@", [job sn]);
}

在控制台中,我明白了:

2014-04-22 15:40:46.464 test[2442:60b] jsArray: (
        {
        d = "Tue 3-Mar";
        sn = E;
        t = K;
    },
        {
        d = "Tue 3-Mar";
        sn = F;
        t = "Y 1";
    }
)
2014-04-22 15:40:46.466 test[2442:60b] job: {
    d = "Tue 3-Mar";
    sn = E;
    t = K;
}
-[__NSCFDictionary sn]: unrecognized selector sent to instance 0x8fa53b0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[__NSCFDictionary sn]: unrecognized selector sent to instance 0x8fa53b0'

它似乎识别出对象数组和单个对象。为什么它反对属性sn

2 个答案:

答案 0 :(得分:3)

jsArray包含词典。因此jobNSDictionaryNSDictionary没有名为sn的方法。如果您想要键@"sn"的值,那么您需要:

for (NSDictionary *job in jsArray) {
    NSLog(@"job: %@", job);
    NSLog(@"%@", job[@"sn"]);
}

答案 1 :(得分:2)

您的jsArray包含NSDictionaries,因此作业类型为NSDictionary。 您无法从NSDictionary那样检索价值。

使用:

 NSLog(@"%@", [job objectForKey:@"sn"]);