Xcode 解析 JSON 返回 NULL

Posted

技术标签:

【中文标题】Xcode 解析 JSON 返回 NULL【英文标题】:Xcode Parsing JSON Returns NULL 【发布时间】:2016-02-10 10:40:41 【问题描述】:

我在解析一些 JSON 数据时遇到问题,其中包含嵌套数组中的嵌套数组。我尝试解析的单个 JSON 对象如下所示:

  
  "date":1454284800,
  "exercises":[  
       
        "name":"Tricep Skull-Crushers",
        "sets":"5",
        "reps":"12",
        "time":"20",
        "weight":"",
        "notes":"testing testing again testing this app which is great "
     ,
       
        "name":"Barbell Squat",
        "sets":"3",
        "reps":"12",
        "time":"",
        "weight":"45",
        "notes":"some notes"
     
  ]
 

我希望将任意数量的这些对象解析为NSDictionary。我之前用JSON 数据成功地做到了这一点,只是没有在嵌套数组中使用嵌套数组。我目前正在使用 NSURLSessionDataTask 从 URL 中检索数据,一旦获得数据,我将其转换为 NSDictionary 并使用以下代码将数据拆分为数组:

        theDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];

        self.namesArray = [[NSMutableArray alloc] init];
        self.setsArray = [[NSMutableArray alloc] init];
        self.repsArray = [[NSMutableArray alloc] init];

        for (NSDictionary *dict in theDictionary) 

            [self.namesArray addObject:[dict objectForKey:@"name"]];
            [self.setsArray addObject:[dict objectForKey:@"sets"]];
            [self.repsArray addObject:[dict objectForKey:@"reps"]];
        

此代码在之前解析 JSON 数据时有效,虽然我可以正确返回数据和响应字符串,但每当我尝试将数据转换为 NSDictionaryNSArray 时,它都会不断返回 NULL。就像我说的,这段代码以前可以解析JSON,但在JSON 对象中没有这么多嵌套数组。

谁能给我一些关于如何实现这一点的建议?

编辑:

我在下面发布了完整的响应字符串,我收到了上面示例的多个对象。如果有人想在JSON Editor Online 中查看此内容,以了解完整回复的外观:

["date":1454284800,"exercises":["name":"Tricep Skull-Crushers","sets":"5","reps":"12","time":"20","weight":"","notes":"testing testing again testing this app which is great ","name":"Barbell Squat","sets":"","reps":"","time":"","weight":"","notes":""],"date":1454284800,"exercises":["name":"Tricep Skull-Crushers","sets":"5","reps":"12","time":"20","weight":"","notes":"testing testing again testing this app which is great ","name":"Barbell Squat","sets":"","reps":"","time":"","weight":"","notes":"","name":"Arnold Press","sets":"5","reps":"12","time":"","weight":"","notes":""],"date":1454112000,"exercises":["name":"Single Arm Row","sets":"3","reps":"10","time":"","weight":"","notes":"","name":"Tricep Rope Pull-Downs","sets":"3","reps":"10","time":"","weight":"","notes":""],"date":1454112000,"exercises":["name":"Single Arm Row","sets":"3","reps":"10","time":"","weight":"","notes":"","name":"Tricep Rope Pull-Downs","sets":"3","reps":"10","time":"","weight":"","notes":""],"date":1454112000,"exercises":["name":"Single Arm Row","sets":"3","reps":"10","time":"","weight":"","notes":"","name":"Tricep Rope Pull-Downs","sets":"3","reps":"10","time":"","weight":"","notes":""]] 

【问题讨论】:

您的 JSON 响应中没有键 workout_nameworkout 那么NSError 对象说了什么? for (NSDictionary *dict in theDictionary[@"exercises"])?? NULL 到底是什么? @Anbu.Karthik 抱歉,这些键是指正在成功运行的应用程序的另一部分。我从我的应用程序的那部分复制并粘贴了工作代码。我现在已经编辑了这个问题,感谢您指出这一点,但这不是我担心的问题。 但是 JSON 中的***对象当然是一个数组,而不是字典,所以你需要更正它。而且你不需要NSJSONReadingMutableContainers,所以改为0。使用局部变量,如下所示:NSArray *array = [NSJSONSerialization ...]; 【参考方案1】:

所以我们终于找到了问题所在。似乎 JSON 在解析换行符 (\n) 时存在问题。我要做的就是将 JSON 数据转换为字符串,删除所有换行符 (\n),然后将字符串转换回数据并将其转换为 NSDictionary。这有点烦人,这花了一天的时间来弄清楚这是一件非常简单的事情,但这是我正在使用的最终代码。希望这可以帮助陷入类似问题的任何人。

        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];

        NSData *dataWithoutLineBreaks = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

        NSError *jsonError;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:dataWithoutLineBreaks options:NSJSONReadingMutableContainers error:&jsonError];

【讨论】:

【参考方案2】:

这是你的答案,用 swift 写出来:

do  
     let json = try NSJsonSerialization.jsonObjectWithDat(jsondata, options: .AllFragments)
for var i = 0 ; i < json.count ; i++ 
    if let item = json[i] 
        if let date = item["date"]//do anything
        if let experience = item["experience"] 
           for ex in experience 
              let name = experience["name"]
              let step = experience["step"]
              let reps = experience["reps"]
              let time = experience["time"]
              let weight = experience["weight"]
              let notes = experience["notes"]
            
      
   catch err as NSError 
     print(err)
  

【讨论】:

【参考方案3】:

您的代码中的一切都正常,只是 for 循环中的一个小改动

for (NSDictionary *dict in theDictionary[@"exercises"]) 


        [self.namesArray addObject:[dict objectForKey:@"name"]];
        [self.setsArray addObject:[dict objectForKey:@"sets"]];
        [self.repsArray addObject:[dict objectForKey:@"reps"]];




    

【讨论】:

恐怕这不起作用,因为我什至无法将数据转换为 NSDictionary 或 NSArray。 检查你的 nsdata 是否有任何值或者它是 nil 是的,数据返回正确,我什至可以将其转换为字符串来确认。问题是将这些数据转换为 NSDictionary 甚至 NSArray。 你了解valueForKey和objectForKey的区别吗?为什么你同时使用它们?为什么不只是字典 [@"exercises"]?

以上是关于Xcode 解析 JSON 返回 NULL的主要内容,如果未能解决你的问题,请参考以下文章

使用 gson 解析成 POJO 时,Json 总是返回 null

hive 踩坑 get_json_object 返回NULL或部分可解析部分解析不了

GSON JSON解析返回null

JSON 解析返回 null 到 iOS(json 字符串看起来正确)

php使用json_decode解析json返回NULL

Gson 解析服务端返回的多种类型的 JSON