只要是app开发者都知道,从服务器端获得的数据要不就是json格式的数据,要么就是xml格式的数据,这篇主要介绍怎么怎么读取json数据,json读取出来时data格式的,一般使用NSJSONSerialization对象来读取文件,来返回json数据,对读取的数据进行分析,有的数据读取出来有数组,有字典,数组中含有字典等等。
接下来以一个小demo的形式说说怎么读取json数据:自己先准备一个本地的json格式文本为待会使用到做好准备。
- 1.创建一个单个的应用程序
- 2.找到UIViewController类
如下实现:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//获得本地json数据的路径
guard let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") else {
print("Error finding file")
return
}
//异常处理
do {
//将获得json数据转换为data格式数据
let data: NSData? = NSData(contentsOfFile: path)
//将data序列化,并且判断是否属于字典类型数据结构
if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
//根据键值对取出数据字典
let dataDictionary = jsonResult["list"] as! NSDictionary
let total = dataDictionary["total"]
print("total items : \(total!)");
let itemArray = dataDictionary["item"] as! NSArray
//循环取出itemArray数组中的数据
for item in itemArray {
let group = item["group"]!
let offset = item["offset"]!
let name = item["name"]!
let ndbno = item["ndbno"]!
print("Item \(offset!): \(group!) - \(name!) - \(ndbno!)")
}
}
} catch let error as NSError {
print("Error:\n \(error)")
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}}
code偏向于简单!