在用Swift
測(cè)試數(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.}
原來(lái)是本地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)
}