我必须在iOS上解析此JSON。

{
"log_by_dates": {
    "logs": [
        {
            "date": "Wednesday 5 December 2012",
            "exercises": "0",
            "workouts": "0",
            "log_entries": "0"
        },
        {
            "date": "Tuesday 4 December 2012",
            "exercises": "4",
            "workouts": "2",
            "log_entries": "7"
        }
    ]
 }
}


我已经编写了以下代码来解析它;

NSArray *logs = [[(NSDictionary*)results objectForKey:@"log_by_dates"] objectForKey:@"logs"];
        for (NSDictionary *aLog in logs) {
            Log *newLog = [[Log alloc] initWithDate:[aLog objectForKey:@"date"]               withExercises:[aLog objectForKey:@"exercises"]
                                       withWorkouts:[aLog objectForKey:@"workouts"]];
            if (!data) {
               data = [[NSMutableArray alloc] init];
            }


但是问题在于,有时候我会得到这样的JSON值;

{

"log_by_dates": {
    "logs":
        {
            "date": "Wednesday 5 December 2012",
            "exercises": "0",
            "workouts": "0",
            "log_entries": "0"
        }
  }
}


这使我的代码崩溃。

请指导我,如果使用if()else条件,我将在解析之前检查传入的JSON对象是否包含单个记录的多个记录,以便我编写适当的代码来处理字典或数组。
谢谢,

最佳答案

请像这样更新您的代码。

NSArray *logs = [[(NSDictionary*)results objectForKey:@"log_by_dates"] objectForKey:@"logs"];
if([logs isKindOfClass:[NSArray class]]) {
    for (NSDictionary *aLog in logs) {
        Log *newLog = [[Log alloc] initWithDate:[aLog objectForKey:@"date"]               withExercises:[aLog objectForKey:@"exercises"]
                                   withWorkouts:[aLog objectForKey:@"workouts"]];
        if (!data) {
            data = [[NSMutableArray alloc] init];
        }
    }
}
else if([logs isKindOfClass:[NSDictionary class]]) {
    NSDictionary *aLog = (NSDictionary *)logs;
    Log *newLog = [[Log alloc] initWithDate:[aLog objectForKey:@"date"]               withExercises:[aLog objectForKey:@"exercises"]
                               withWorkouts:[aLog objectForKey:@"workouts"]];
    if (!data) {
        data = [[NSMutableArray alloc] init];
    }
}

关于objective-c - 如何检查传入的JSON feed是否包含单个记录或多个记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13717806/

10-10 20:44