加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

iOS Swift读取本地json文件报错的解决方法

发布时间:2020-12-16 20:01:34 所属栏目:百科 来源:网络整理
导读:前言 最近闲来无聊,本地了一个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={N

前言

最近闲来无聊,本地了一个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)
  }

扩展阅读--苹果官网 Error Handling

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读