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

原本是当地jsonjson,文本前面有一段注释/* 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)
        }

扩大阅读–苹果官网 Error
Handling

相关文章

网站地图xml地图