JSON解码不起作用

时间:2018-06-03 18:24:09

标签: json swift

我想使用和解析CuteRadioAPI的无线电列表 http://marxoft.co.uk/doc/cuteradio-api/stations/

GET请求的结果是这样的: http://marxoft.co.uk/api/cuteradio/stations?limit=2&sort=title&sortDescending=false&approved=1&offset=50%22}

似乎它不是真正的JSON结构......

我试着像这样解码它:

struct Radio:Codable {
    var approved: Bool?
    var country: String?
    var creatorId: Int?
    var description: String?
    var genre: String?
    var id: Int?
    var language: String?
    var lastPlayed: String?
    var playCount: Int?
    var source: String?
    var title: String?
}

struct CuteRadioReturn:Codable {
    var Radios : [Radio]
}


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 {
            self.showAlert(title: "Erreur réseau", message: "\(error!.localizedDescription)")
            return
        }
        guard let data = data else {
            self.showAlert(title: "Erreur données", message: "Liste des radios non disponible !")
            return
        }

        do {
            print ("try")

            guard let radios = try? JSONDecoder().decode(CuteRadioReturn.self, from: data) else {
                print("Error: Couldn't decode JSON")
                return
            }

        }

        print (radios.Radios.count)

}
task.resume()

我总是在无线电中得到零......

有什么想法可以提供帮助吗?

2 个答案:

答案 0 :(得分:0)

响应是字典而不是数组,它的主键是项目将其更改为

struct CuteRadioReturn:Codable {
  var items : [Radio]
  var next:String
}

答案 1 :(得分:-1)

将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()