DecodeJSON
示例
要运行示例项目,请克隆仓库,然后首先从示例目录运行 pod install
安装
DecodeJSON 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile
pod 'DecodeJSON'
使用
首先,您需要一个用于响应的 struct。
struct BookResponse: Codable {
let ID: Int
let Title: String
let Description: String
let PageCount: Int
}
您还可以使用编码键创建结构体来自定义自己的名称。
struct BookResponse: Codable {
let id: Int
let title: String
let description: String
let numberOfPages: Int
enum CodingKeys : String, CodingKey {
case id = "ID"
case title = "Title"
case description = "Description"
case numberOfPages = "PageCount"
}
}
要解码请求中的 JSON,您可以像以下示例中那样做。
let url = URL(string: "https://fakerestapi.azurewebsites.net/api/Books")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
if let books: [BookResponse] = DecodeJSON.shared.decode(data: data) {
print(books)
}
}
task.resume()
作者
jmhdevep,[email protected]
授权协议
DecodeJSON 可在 MIT 协议下使用。有关更多信息,请参阅 LICENSE 文件。