亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用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 關注
  • 867 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號