前言
最近閑來無聊,本地了一個(gè)json讀取,但沒想到在用Swift測試數(shù)據(jù)發(fā)現(xiàn)加載本地json文件一直報(bào)以下錯(cuò)誤:
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! 的區(qū)別 * try 發(fā)生異常會(huì)跳到catch代碼中 * try! 發(fā)生異常程序會(huì)直接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("讀取本地?cái)?shù)據(jù)出現(xiàn)錯(cuò)誤!",error) }
擴(kuò)展閱讀--蘋果官網(wǎng) Error Handling
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選