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

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

发布时间:2020-12-14 01:42:11 所属栏目:百科 来源:网络整理
导读:我的json数据文件放到了datas目录下:右键该目录,使用“add files to” 把projectTimeList.txt加到该目录,形成结构如下: projectTimeList.txt的内容如下: {"ResultCode":2,"Record":[{"pid":"p001","pname":"山洪灾害监测预警","budget":80,"profit":20,

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



projectTimeList.txt的内容如下:

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

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

 //文件路径获取
        let pathFull=NSBundle.mainBundle().pathForResource("projectTimeList",ofType: "txt")!
        do{
            //读取文件
            let jsonData=NSData(contentsOfFile: pathFull)!
            //转成json对象
            let jsonObject : AnyObject! = try NSJSONSerialization.JSONObjectWithData(jsonData,options: NSJSONReadingOptions.MutableContainers )
            //把record转为数组
            if let statusesArray = jsonObject.objectForKey("Record") as? NSMutableArray{
                for arow in statusesArray{
                    //取出属性值
                    print(arow["pname"])
                   
                }
            }
        }catch let error as NSError{
            print(error.localizedDescription)
        }

(编辑:李大同)

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

    推荐文章
      热点阅读