Swift中的字典转模型方法的迭代

2018/10/30 posted in  iOS

模型可以是结构体也可以是继承自NSObject的类

class App: NSObject {
    var name:String = ""
    var age:Int = 0
    var boxDescription:String = ""
}


struct App :Decodable{
    var name:String
    var age:Int
    var description:String
    
    init(dic:[String:AnyObject]) {
        name = dic["name"] as! String
        age = dic["age"] as! Int
        description = dic["description"] as! String
    }
    
}

网络请求

 func fetchData(){
        let url = "https://maweefeng.github.io/appfeauterd.json"
        
        let session: URLSession = URLSession.shared
        
        let dataTask: URLSessionDataTask = session.dataTask(with: URL(string: url)!) { (data, response, error) in
            if(error == nil){
                var dict:NSDictionary? = nil
                do {
                    guard let jsondata = data else{return}
                    let app = try JSONDecoder().decode(App.self, from: jsondata)
                    print(app)
                    
//dict = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
//
//                    let app = App(dic: dict)
//                    print(app)

                    
                } catch {
                }
                print(dict!)
            }
        }
        dataTask.resume()
        
    }

JSONSerialization

之前我们字典转模型可能使用的方法可能是使用

  • model为结构体

    dict = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
    let app = App(dic: dict)
    print(app)
  • model为NSObject子类

    dict = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
    let app = App()
    app.setValuesForKeys(dict as! [String : Any])

JSONDecode

现在使用swift4新增了一种更方法的方法,就是JSONDecode

let app = try JSONDecoder().decode(App.self, from: jsondata)`

如果返回的data数据是一个object的字典,那么可以用上面的代码

如果data是一个包含app对象的数组,则可以简单的使用

let app = try JSONDecoder().decode([App].self, from: jsondata)`

另外一些情况,可能数组当中并不是每个键值对都一一对应,可能存在部分键值对缺失的情况,这样的话就会报错,有一个解决办法便是使那些可以为空的属性为optional,这样就可以解决错误问题。