使用 Codable 协议快速生成 model 0 个改进

如果你只是需要一个 model 来格式化 JSON 格式的值类型数据,可以使用 Swift 4 中推出的 Codable 协议,该协议为 DecodableEncodable 两个协议的集合( typealias ),帮助我们快速的格式化数据。假设我们的 JSON 数据格式如下:

{
    "citys": [
        {
            "latitude": 39.9889416194,
            "longitude": 116.3826799393
        },
        {
            "latitude": 39.9889416194,
            "longitude": 116.3826799393,
            "address": {
                "city": "Beijing",
                "formatterAddress": "北四环中路35号北京信息科技大学"
            }
        }
    ]
}

使用 Codable 协议可以这么写:

struct AnnotationModel: Codable {
    // 纬度
    var latitude: Double
    // 经度
    var longitude: Double
}

当然,它也支持嵌套:

struct AnnotationModel: Codable {

    struct details: Codable {
        // 城市
        var city: String
        // 格式化地址
        var formatterAddress: String
    }
    // 地点信息
    var address: [details]
    // 纬度
    var latitude: Double
    // 经度
    var longitude: Double
}

JSON 数据格式化:

if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) {
    if let annotationModel = try? JSONDecoder().decode(AnnotationModel.self, from: jsonData) {
             // 写下转换完后你需要做的事情......
         }
}
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!