JSON数据的存、取
2016-08-25 本文已影响13人
Dove_Q
ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let ani = Animal()
ani.name = "Dog"
ani.weight = 20
ani.age = 3
//to JSON String -> File
//字典/数组
let dict = ani.toDict()
//NSData
let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
let s = NSString(data: data, encoding: NSUTF8StringEncoding)
print(s!)
let path1 = NSHomeDirectory() + "/Documents/1.json"
try! data.writeToFile(path1, options: .AtomicWrite)
let path2 = NSHomeDirectory() + "/Documents/2.json"
try! s?.writeToFile(path2, atomically: true, encoding: NSUTF8StringEncoding)
print(path1)
let data2 = NSData(contentsOfFile: path1)
let dict2 = try! NSJSONSerialization.JSONObjectWithData(data2!, options: .AllowFragments) as! NSDictionary
let ani2 = Animal(dict: dict2)
print(ani2.name, ani2.age, ani2.weight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Animal类
class Animal: NSObject {
var weight: Double = 0
var name: String!
var age: Int = 0
override init() {
super.init()
}
init(dict: NSDictionary) {
super.init()
//一定要检查安全性
if let n = dict["name"] as? String {
name = n
}
age = dict["age"] as! Int
weight = dict["weight"] as! Double
}
func toDict() -> Dictionary<String, AnyObject> {
var dict = Dictionary<String, AnyObject>()
dict["name"] = "Dog"
dict["weight"] = 20
dict["age"] = 3
return dict
}
}