为了账号安全,请及时绑定邮箱和手机立即绑定

使用Swift读取JSON文件

使用Swift读取JSON文件

一只斗牛犬 2019-12-09 11:01:02
我真的很努力尝试将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? NSDictionaryprintln("jsonDict \(jsonDict)") - This prints nil..... 如果有人可以在正确的方向上向我推销我如何反序列化JSON文件并将其放在可访问的Swift对象中,我将万分感谢!亲切的问候,Krivvenz。
查看完整描述

3 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

请遵循以下代码:


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

            }

        }

     }

}

数组“人员”将包含关键人员的所有数据。遍历以获取它。


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

      }

}


查看完整回答
反对 回复 2019-12-09
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

更新:

对于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.")

}


查看完整回答
反对 回复 2019-12-09
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

使用Decodable的Swift 4


struct ResponseData: Decodable {

    var person: [Person]

}

struct Person : Decodable {

    var name: String

    var age: String

    var employed: String

}


func loadJson(filename fileName: String) -> [Person]? {

    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {

        do {

            let data = try Data(contentsOf: url)

            let decoder = JSONDecoder()

            let jsonData = try decoder.decode(ResponseData.self, from: data)

            return jsonData.person

        } catch {

            print("error:\(error)")

        }

    }

    return nil

}

迅捷3


func loadJson(filename fileName: String) -> [String: AnyObject]? {

    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {

        do {

            let data = try Data(contentsOf: url)

            let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)

            if let dictionary = object as? [String: AnyObject] {

                return dictionary

            }

        } catch {

            print("Error!! Unable to parse  \(fileName).json")

        }

    }

    return nil

}


查看完整回答
反对 回复 2019-12-09
  • 3 回答
  • 0 关注
  • 769 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信