ios - NSJSONSerialization 不将数据存储到数组中

标签 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

最佳答案

发生这种情况是因为您的 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"];

关于ios - NSJSONSerialization 不将数据存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966971/

相关文章:

json - .net Core 和 Serilog 电子邮件接收器 - json 配置

iOS SDK - 与 socket 建立连接的正确方法?

android - Android上的任务队列就像iOS上的GCD一样?

ios - Sprite 套件中的 UIScrollView

objective-c - (NSTimer) 创建一个计时器倒计时

ios - swift - 如何从服务器获取 JSON 响应

iOS DIsptchqueue.global 错误

ios - displaysSearchBarInNavigationBar 不显示搜索栏

ios - Youtube iframe 未显示在 UIWebView 中

java - Jackson:如何使用简写属性值反序列化 json