美文网首页
8.25 JSON -> File

8.25 JSON -> File

作者: jayck | 来源:发表于2016-09-07 20:59 被阅读7次

    新建类 Animal

    import UIKit
    
    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
        }
    }
    

    回到ViewController

    import UIKit
    
    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.
        }
    }
    

    运行结果如下:

    Paste_Image.png

    相关文章

      网友评论

          本文标题:8.25 JSON -> File

          本文链接:https://www.haomeiwen.com/subject/jbtsettx.html