swift开发笔记14 - 解析json数据文件

前端之家收集整理的这篇文章主要介绍了swift开发笔记14 - 解析json数据文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的json数据文件放到了datas目录下:右键该目录,使用“add files to” 把projectTimeList.txt加到该目录,形成结构如下:



projectTimeList.txt的内容如下:

  1. {
  2. "ResultCode":2,"Record":[
  3. {
  4. "pid":"p001","pname":"山洪灾害监测预警","budget":80,"profit":20,"cost":[10,20,22,19,14,10]
  5. },{
  6. "pid":"p002","pname":"小流域洪水分析","budget":100,"profit":50,"cost":[20,23,10,4,2]
  7. }
  8. ]}
可以到在线json格式验证网站上,验证格式是否正常: http://json.cn

代码中读取该文件并解析的代码如下(不需要第三方类库)

  1. //文件路径获取
  2. let pathFull=NSBundle.mainBundle().pathForResource("projectTimeList",ofType: "txt")!
  3. do{
  4. //读取文件
  5. let jsonData=NSData(contentsOfFile: pathFull)!
  6. //转成json对象
  7. let jsonObject : AnyObject! = try NSJSONSerialization.JSONObjectWithData(jsonData,options: NSJSONReadingOptions.MutableContainers )
  8. //把record转为数组
  9. if let statusesArray = jsonObject.objectForKey("Record") as? NSMutableArray{
  10. for arow in statusesArray{
  11. //取出属性
  12. print(arow["pname"])
  13. }
  14. }
  15. }catch let error as NSError{
  16. print(error.localizedDescription)
  17. }

猜你在找的Swift相关文章