To run the example project, clone the repo, and run pod install from the Example directory first.
DecodeJSON is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'DecodeJSON'First you need to create a struct for the response.
struct BookResponse: Codable {
let ID: Int
let Title: String
let Description: String
let PageCount: Int
}Also you can created the struct with coding keys to assigning your own names.
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"
}
}To decode a JSON in a request you can do it like in this example.
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, jmherrero@jmhdeveloper.com
DecodeJSON is available under the MIT license. See the LICENSE file for more info.