Для использования Codable с json Любой словарь, преобразованный в struct или class
В Json {}
- это словарь, а []
- это массив
, согласно этой модели ваша модель будет
Модель:
import Foundation
struct CuteRadioReturn: Codable {
let items: [Radio]
let next: String
}
struct Radio: Codable {
let id: Int
let title, description, genre, country: String
let language, source: String
let playCount: Int
let lastPlayed: String
let creatorID: Int
let approved: Bool
enum CodingKeys: String, CodingKey {
case id, title, description, genre, country, language, source, playCount, lastPlayed
case creatorID = "creatorId"
case approved
}
}
// MARK: Convenience initializers
extension CuteRadioReturn {
init(data: Data) throws {
self = try JSONDecoder().decode(CuteRadioReturn.self, from: data)
}
}
И вызов API
let url = URL(string: "http://marxoft.co.uk/api/cuteradio/stations")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
if let cuteRadioReturn = try? CuteRadioReturn.init(data: data){
print(cuteRadioReturn.items)
}
}
task.resume()