Ios 尝试使用Swift表达JSON时出错

Ios 尝试使用Swift表达JSON时出错,ios,arrays,json,swift,jsondecoder,Ios,Arrays,Json,Swift,Jsondecoder,我试图从Mac上Swift Played中的JSON链接接收数据,我已经构造了所有数据,但我在尝试解码所有数据时遇到问题,接收到错误:“在'Array'上引用实例方法'decode(:from:)'需要'Bicimia'符合'Decodable'” 我已经尝试添加Codable/Decodable选项,并尝试分别更改URLSession,但没有任何更改 struct Bicimia { let network: Network } struct Network { le

我试图从Mac上Swift Played中的JSON链接接收数据,我已经构造了所有数据,但我在尝试解码所有数据时遇到问题,接收到错误:“在'Array'上引用实例方法'decode(:from:)'需要'Bicimia'符合'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()

要想
可解码
所有属性都应该
可解码

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
}

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

按照错误建议执行:将一致性添加到所有结构中<代码>结构…:Decodable{我已经尝试将:Decodable添加到所有结构中,但我收到一个错误,上面说:“Type'Extra'不符合协议'Decodable'”将一致性添加到
Decodable
以及枚举
状态
类型“Status”不符合协议“Decodable”查看JSON
状态
有案例
在线
离线
因此将枚举更改为
枚举状态:字符串,可解码{case online,offline}
工作正常,但现在在终端中我收到一个错误:“typemissmatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“应该解码数组,但是找到了一个字典。”,underlineerror:nil))“使用
让res=尝试jsondeconder().decode(Bicimia.self,from:data!)”而不是[Bicimia.self]…这是另一个问题,但您应该按照@StephanSchlecht所述进行解码。请不要在评论中提出其他问题。除非,如果需要,请随时提问。如果这是您所说的原始问题的答案,请别忘了标记为答案。