NSJSONSerialization不将数据存储到数组中

时间:2016-06-22 11:39:55

标签: ios objective-c json

我在AppDelegate.m中有这段代码:

    NSError *error;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"City" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSArray *json = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments error:&error];


    NSLog(@"data : %@",data);
    NSLog(@"json : %@",json[0]);

data包含内容但NSJSONSerialization未将其存储到变量json中(显示(null)

我的json文件内容:

[

“Result”:
 {
   "ID":"3",
   "Name":"Ambegaon",
   "Distid":"1050114"
 },
 {
   "ID":"4",
   "Name":"Aundh",
   "Distid":"1050114"
 }
]

我尝试过的事情:

  1. NSDictionary NSArray可变和不可变

  2. 更改了City.json位置

  3. NSJSONReadingMutableContainers NSJSONReadingMutableLeaves kNilOptions

  4. 等不同选项

2 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为您的JSON格式无效。它不等于数组。你需要

[
 {
   "ID":"3",
   "Name":"Ambegaon",
   "Distid":"1050114"
 },
 {
   "ID":"4",
   "Name":"Aundh",
   "Distid":"1050114"
 }
]

没有Result键或将您的json和解析代码更改为

{
   "Result" : [{
      "ID":"3",
      "Name":"Ambegaon",
      "Distid":"1050114"
    },
    {
      "ID":"4",
      "Name":"Aundh",
      "Distid":"1050114"
    }]
}

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                    options:NSJSONReadingAllowFragments error:&error];
NSArray *arr = json[@"Result"];

答案 1 :(得分:0)

如果JSON数据格式错误,方法jsonObjectWithData将失败。

JSON数据的语法一定有问题。您可以将NSData转换为字符串并记录该字符串。您也可以检查从函数中返回的错误。

相关问题