WWDC-2017笔记---Codable

WWDC,iOS,Codable

Posted by Karim on June 21, 2017

在swift中并不推荐使用runtime,所以json转model比较麻烦,而且也不支持structenum

但是现在可以通过Codable来实现,实现一个这样的结构体

public struct DataListResult:Codable{
    let _id : String?
 
    let images : Array<String>?

}
public struct DataListModel:Codable{
    let results : [DataListResult]?
    let error: Bool?
}
//一段JSON
 {
      "_id" : "592502d6421aa92c769a8bac",
      "images" : [
        "http:\/\/img.gank.io\/44e8aa0a-b66f-4a5b-9cb0-74c3ae9fc156"
      ],
    },
    {
      "_id" : "5923a438421aa92c73b64743",
      "images" : [
        "http:\/\/img.gank.io\/25762b53-b2ba-4c1c-9666-1683cd72bb82"
      ],
    }
  ],
  "error" : false
//JSON data转模型
let model = try? JSONDecoder().decode(DataListModel.self, from: response.data!) 
//模型转JSON data
let data =  try? JSONEncoder().encode(model)

在看Session 212的时候,发现了还有别的一些用法,像是时间,可以通过以下方法转换成Date

let jsonData = """
{
  "name": "Monalisa Octocat",
  "email": "support@github.com",
  "date": "2011-04-14T16:00:49Z"
}
""".data(using: .utf8)!
struct Author : Codable {
  let name: String
  let email: String
  let date: Date
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let author = try? decoder.decode(Author.self, from: jsonData)

最近也有用到这部分功能,补充一下获取到的json对应key和model的字段不一样的情况

{
"nickname" : 'fidetro',
"birthday": "1994-10-14"
}

struct Person : Codable  {
    var name : String?
    var date :Date?
 
    private enum CodingKeys: String,CodingKey {
        case name = "nickname"
        case date = "birthday"
    }
    
}

这时候要注意CodingKeys是需要把所有的key都case出来,不然会报这样的错


请保持转载后文章内容的完整,以及文章出处。本人保留所有版权相关权利。

分享到: