Swift 4 引入了一个新的 Codable
协议,它允许您将自定义数据类型序列化和反序列化,而无需编写任何特殊代码,也不必担心丢失值类型。
太棒了,不是吗?这个库可以帮助您编写更少的代码!它是 Alamofire
的一个扩展,可以将 JSON
数据转换为 Decodable
对象。
有用资源
- 自定义类型的编码和解码 - Apple 文章
- 使用自定义类型与 JSON - Swift 演示项目
- 此外,在
WWDC2017
中也有一个特别的会话涵盖了这个新特性 - Foundation 中新增的功能
用法
让我们使用以下 Swift 模型反序列化一个简单的 json 文件
{
"result": {
"libraries": [
{
"name": "Alamofire",
"stars": 23857,
"url": "https://github.com/Alamofire/Alamofire",
"random_date_commit": 1489276800
},
{
"name": "RxSwift",
"stars": 9600,
"url": "https://github.com/ReactiveX/RxSwift",
"random_date_commit": 1494547200
}
]
}
}
(此处应有 Swift 模型示例)
private struct Repo: Decodable {
let name: String
let stars: Int
let url: URL
let randomDateCommit: Date
private enum CodingKeys: String, CodingKey {
case name
case stars
case url
case randomDateCommit = "random_date_commit"
}
}
有一个类似的方法 responseData
和 responseJSON
- responseDecodableObject
func responseDecodableObject<T: Decodable>(queue: DispatchQueue? = nil, keyPath: String? = nil, decoder: JSONDecoder = JSONDecoder(), completionHandler: @escaping (AFDataResponse<T>) -> Void)
queue
- 将完成处理程序派发的队列。keyPath
- 对象解码要执行的关键路径。decoder
- 用于将 JSON 解码为语义上Decodable
类型的解码器。
let url = URL(string: "https://raw.githubusercontent.com/otbivnoe/CodableAlamofire/master/keypathArray.json")!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970 // It is necessary for correct decoding. Timestamp -> Date.
AF.request(url).responseDecodableObject(keyPath: "result.libraries", decoder: decoder) { (response: AFDataResponse<[Repo]>) in
let repo = response.value
print(repo)
}
注解
- 对于数组:
DataResponse<[Repo]>
- 对于单个对象:
DataResponse<Repo>
要求
- Swift 4+
- Xcode 9+
🔥
安装CocoaPods
CocoaPods 是 Swift 和 Objective-C Cocoa 项目的依赖管理器。它拥有超过一万八千个库,并可以帮助您优雅地扩展您的项目。您可以使用以下命令安装它:
$ sudo gem install cocoapods
要集成 CodableAlamofire,只需在您的 Podfile
中添加以下行:
target 'Test' do
use_frameworks!
pod 'CodableAlamofire'
end
Carthage
Carthage 是一个去中心化的依赖管理器,它可以构建您的依赖并提供二进制框架。
您可以使用以下命令使用 Homebrew 安装 Carthage:
$ brew update
$ brew install carthage
要使用 Carthage 将 CodableAlamofire 集成到您的 Xcode 项目中,请在您的 Cartfile
中指定它。
github "Otbivnoe/CodableAlamofire"
运行 carthage update
以构建框架,然后将构建的 CodableAlamofire.framework
拖放到您的 Xcode 项目中。