使用 Codable 协议快速生成 model
如果你只是需要一个 model
来格式化 JSON
格式的值类型数据,可以使用 Swift 4
中推出的 Codable
协议,该协议为 Decodable
和 Encodable
两个协议的集合( 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) {
// 写下转换完后你需要做的事情......
}
}