【问题标题】:How to check that the incoming JSON feed contains a single record or multiple?如何检查传入的 JSON 提要是否包含单条记录或多条记录?
【发布时间】:2012-12-05 06:51:19
【问题描述】:

我必须在 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 对象是否包含单个记录的多个记录,以便我编写适当的代码来处理字典或数组。 谢谢,

【问题讨论】:

  • 它是如何崩溃的,错误信息是什么?

标签: objective-c ios json nsarray nsdictionary


【解决方案1】:

请像这样更新您的代码。

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];
    }
}

【讨论】:

    【解决方案2】:

    检查条件

    if([[[(NSDictionary*)results objectForKey:@"log_by_dates"] objectForKey:@"logs"] isKindOfClass:[NSArray class]])
    {
        // Do your Array Stuff Here
    } else {
        // Do your Dictionary Stuff Here
    }
    

    【讨论】:

      【解决方案3】:

      for 循环之前插入:

      if (![logs isKindOfClass:[NSArray class]])
      {
          logs = [NSArray arrayWithObject:logs];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多