在用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)
}