我的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) }