I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....

我的JSON文件名为test.json并包含以下内容:

{
  "person":[
     {
       "name": "Bob",
       "age": "16",
       "employed": "No"
     },
     {
       "name": "Vinny",
       "age": "56",
       "employed": "Yes"
     }
  ]
}    

文件直接存储在文档中,我使用以下代码访问它:

let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
                                                          NSSearchpathDirectory.DocumentDirectory,
                                                          NSSearchPathDomainMask.AllDomainMask,
                                                          true) as String[]

if (dirs != nil) {
    let directories: String[] = dirs
    let dir = directories[0]
    let path = dir.stringByAppendingPathComponent(file)
}

var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.

var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary

println("jsonDict \(jsonDict)") - This prints nil..... 

如果有人能给我一个正确的方向,告诉我如何反序列化JSON文件,并将其放入一个可访问的Swift对象中,我将永远感激!

亲切的问候,

Krivvenz.

推荐答案

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
    {
        if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
        {
            if let persons : NSArray = jsonResult["person"] as? NSArray
            {
                // Do stuff
            }
        }
     }
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
                    // do stuff
          }
      } catch {
           // handle error
      }
}

Json相关问答推荐

如何抓住引号之间的第二次出现?

震击:三针并用震击

如何在PowerShell中扩展JSON中的嵌套数组

当console.log返回TRUE值时,解析的JSON中的字段未定义

在AWS步骤函数中将字符串解析为JSON&S映射状态

Powershell ConvertFrom-Json 意外地从包含字符串的单个项目数组生成字符串而不是对象数组

使用 jq 重新格式化 JSON 输出

Jolt 不打印任何东西

使用jq根据对象中键的值查找对象

派生类的属性没有得到价值

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

如何用 Xidel 正确读取这个 JSON 文件?

JSON.NET 中特定对象的自定义转换

Android JSON 库的性能和可用性比较

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

如何创建 JSON 对象 Node.js

在 Webpack 中加载静态 JSON 文件

Java循环遍历Json数组?

Jackson:忽略 Json 配置值

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器