README.md
{
"total_count": 176552,
"incomplete_results": false,
"items": [
{...}
]
}
class GithubRepository: NSObject, Mappable {
var id : String = ""
var name : String = ""
var body : String = ""
var url : String = ""
var photo : String = ""
var createdAt : Date?
}
class GithubSearch: NSObject, Mappable {
var total : Int = 0
var items : [GithubRepository] = []
}
使用mapFromDictionary
属性可以自定义属性映射。您还可以访问字典和数组中的嵌套值(例如:emails.0.address
)。
var mapFromDictionary: [String : String] {
return [
"body" : "description",
"photo" : "owner.avatar_url",
"createdAt" : "created_at"
]
}
mapFromDictionaryTypes
属性允许您自定义JSON属性的类型(仅适用于可选类型)。如果您需要使用其他Swift结构,只需使用Mappable
协议来扩展它们。
var mapFromDictionaryTypes: [String : Mappable.Type] {
return [
"createdAt" : Date.self
]
}
例如,createdAt
是类型为Date
的,而JSON属性是类型为String
的。为了将String
转换为Date
类型,只需扩展它使用Mappable
协议,它会自动知道将值转换为模型并设置它。
extension Date: Mappable {
init?(from: Any) {
if let value = from as? String {
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH':'mm':'ss'Z'"
if let date = formatter.date(from: value) {
self.init(timeIntervalSince1970: date.timeIntervalSince1970)
return
}
}
self.init()
}
}
现在您可以从来自网络层的通用字典中填充您的模型了。编码愉快 :)。
Alamofire.request(APIURL).responseJSON { (response) in
if let dictionary = response.result.value as? KeyValue {
self.feed = GithubSearch(dictionary)
}
}