Objective-C Json获取和解析数据

时间:2015-08-13 21:24:06

标签: ios objective-c json

我试图从我的api解析数据。我的代码是正确的。我用了很多时间。但我没有得到这样的错误。我做错了什么。可以。帮帮我?

-(void)getStatu {
    NSURL *urlPath = [NSURL URLWithString:@"http://myurl.com/m/cc/cc_today.php"];
    NSData *jsonData = [NSData dataWithContentsOfURL:urlPath];
    NSError *error = nil;
    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    NSLog(@"%@",dataDictionary);
    _ccStatus = [NSMutableArray array];
    NSArray *statuArray = [dataDictionary objectEnumerator];
    for (NSDictionary *statuDictionary in statuArray) {
        CCStatu *status = [CCStatu statuWithTitle:[statuDictionary objectForKey:@"gelen"]];
        status.cevap = [statuDictionary objectForKey:@"cevap"];
        status.cort = [statuDictionary valueForKeyPath:@"cort"];
        status.kayip = [statuDictionary valueForKeyPath:@"kayip"];
        status.lort = [statuDictionary valueForKeyPath:@"lort"];
        status.tekil = [statuDictionary valueForKey:@"tekil"];
        [_ccStatus addObject:status];
    }

}

这是我的json

2015-08-13 23:54:41.362 CSGB[3215:209292] {
    cevap = "37,627";
    cort = "00:00:48";
    gelen = "54,247";
    kayip = "16,620";
    lort = "00:01:17";
    sl = "46.30 %";
    tekil = "3,316";
}

这是错误

2015-08-13 23:54:58.330 APP[3215:209292] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7fcc12451c30
2015-08-13 23:54:58.336 APP[3215:209292] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7fcc12451c30'

1 个答案:

答案 0 :(得分:1)

您的代码错误地迭代数据。你只有一本字典。没有什么可以迭代的。

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(@"%@",dataDictionary);
_ccStatus = [NSMutableArray array];
CCStatus *status = [CCStatu statuWithTitle:dataDictionary[@"gelen"]];
status.cevap = dataDictionary[@"cevap"];
status.cort = dataDictionary[@"cort"];
status.kayip = dataDictionary[@"kayip"];
status.lort = dataDictionary[@"lort"];
status.tekil = dataDictionary[@"tekil"];
[_ccStatus addObject:status];