尝试用 Swift 来表达 JSON 时出错

Error while trying to phrase JSON with Swift

我正在尝试从 Mac 上 Swift Playground 中的 JSON link 接收数据,我已经构建了所有数据,但我尝试解码所有数据时遇到问题,收到错误:"Referencing instance method 'decode(_:from:)' on 'Array' requires that 'Bicimia' conform to 'Decodable'"

我已经尝试添加 Codable/Decodable 选项,并尝试分别更改 URLSession,但没有任何改变。

struct Bicimia {

    let network: Network

}


struct Network {

    let company: [String]
    let href, id: String
    let location: Location
    let name: String
    let stations: [Station]

}

struct Location {

    let city, country: String
    let latitude, longitude: Double

}

struct Station {

    let emptySlots: Int
    let extra: Extra
    let freeBikes: Int
    let id: String
    let latitude, longitude: Double
    let name, timestamp: String

}

struct Extra {

    let extraDescription: String
    let status: Status

}

enum Status {

    case online
}


let url = "https://api.citybik.es/v2/networks/bicimia"
let urlOBJ = URL(string: url)

URLSession.shared.dataTask(with: urlOBJ!) {(data, response, error) in


    do {
        let res = try JSONDecoder().decode([Bicimia].self, from: data!)
        print(res)
    }
    catch {
        print(error)
    }
}.resume()

要成为 Decodable 所有属性都应 Decodable 链下:

struct Bicimia: Decodable {
    let network: Network // should be decodable
}

struct Network: Decodable {
    let company: [String]
    let href, id: String
    let location: Location // should be decodable
    let name: String
    let stations: [Station] // should be decodable
}

struct Location: Decodable {
    let city, country: String
    let latitude, longitude: Double
}

struct Station: Decodable {
    let emptySlots: Int
    let extra: Extra // should be decodable
    let freeBikes: Int
    let id: String
    let latitude, longitude: Double
    let name, timestamp: String
}

struct Extra: Decodable {
    let extraDescription: String
    let status: Status // should be decodable
}

enum Status: String, Decodable {
    case online
}

注意enums不能单独Decodable,因为他们应该知道什么是原始值,或者你应该在decode函数中手动解码它们。