使用Swift读取JSON文件

我真的很努力尝试将JSON文件读取到Swift中,以便可以使用它。我花了两天的大部分时间来重新搜索并尝试不同的方法,但是到目前为止还没有运气,因此我已经注册了StackOverFlow,以查看是否有人可以向我指出正确的方向.....


我的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。


一只斗牛犬
浏览 824回答 3
3回答

交互式爱情

请遵循以下代码:if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json"){&nbsp; &nbsp; if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let persons : NSArray = jsonResult["person"] as? NSArray&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Do stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}}数组“人员”将包含关键人员的所有数据。遍历以获取它。Swift 4.0:if let path = Bundle.main.path(forResource: "test", ofType: "json") {&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; } catch {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// handle error&nbsp; &nbsp; &nbsp; }}

白衣染霜花

更新:对于Swift 3/4:if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {    do {        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)        let jsonObj = try JSON(data: data)        print("jsonData:\(jsonObj)")    } catch let error {        print("parse error: \(error.localizedDescription)")    }} else {    print("Invalid filename/path.")}

繁星淼淼

使用Decodable的Swift 4struct ResponseData: Decodable {&nbsp; &nbsp; var person: [Person]}struct Person : Decodable {&nbsp; &nbsp; var name: String&nbsp; &nbsp; var age: String&nbsp; &nbsp; var employed: String}func loadJson(filename fileName: String) -> [Person]? {&nbsp; &nbsp; if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let data = try Data(contentsOf: url)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let decoder = JSONDecoder()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let jsonData = try decoder.decode(ResponseData.self, from: data)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return jsonData.person&nbsp; &nbsp; &nbsp; &nbsp; } catch {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("error:\(error)")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return nil}迅捷3func loadJson(filename fileName: String) -> [String: AnyObject]? {&nbsp; &nbsp; if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let data = try Data(contentsOf: url)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let dictionary = object as? [String: AnyObject] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return dictionary&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Error!! Unable to parse&nbsp; \(fileName).json")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return nil}
打开App,查看更多内容
随时随地看视频慕课网APP