前言
最近閑來無聊,本地了一個json讀取,但沒想到在用Swift測試數據發現加載本地json文件一直報以下錯誤:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
原來是本地json文件前面有一段注釋/* chrome-extension://pkgccpejnmalmdinmhkkfafefagiiiad/template/fehelper_jsonformat.html */
然后就讀取不到了```坑啊,去掉注釋就可以正常讀取了
let path = Bundle.main.path(forResource: "countryData", ofType: "json")let url = URL(fileURLWithPath: path!)// 帶throws的方法需要拋異常 do { /* * try 和 try! 的區別 * try 發生異常會跳到catch代碼中 * try! 發生異常程序會直接crash */ let data = try Data(contentsOf: url) let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) let jsonArr = jsonData as! NSArray for dict in jsonArr { print(dict) } } catch let error as Error! { print("讀取本地數據出現錯誤!",error) }
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答