我似乎无法获得解码此 API 的正确结构。这都是字典 ({...}),但我的代码一直试图将其解构为数组。
错误代码:
Error serialising json typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
2018-04-25 22:41:50.570999+0100 APItest[40741:729417] TIC Read Status [1:0x0]: 1:57
2018-04-25 22:41:50.571127+0100 APItest[40741:729417] TIC Read Status [1:0x0]: 1:57
解析API链接: https://api.coinbase.com/v2/exchange-rates?currency=BTC
代码:
func mainExchanges(){
let jsonUrlString = "https://api.coinbase.com/v2/exchange-rates?currency=BTC"
guard let url = URL(string: jsonUrlString) else
{ return }
URLSession.shared.dataTask(with: url)
{ (data,response,err) in
guard let data = data else
{
print("Error: No data to decode")
return
}
do
{
let exchanges = try
JSONDecoder().decode([Exchanges].self, from: data)
print(exchanges[0].data.rates.EUR)
}
catch let jsonErr
{
print("Error serialising json",jsonErr)
}
}
.resume()
}
结构:
struct Exchanges: Decodable {
let data: currency
struct currency: Decodable {
let currency: String
let rates: Rates
struct Rates: Decodable {
let GBP: String
let EUR: String
let USD: String
}
}
}
我也试过将其构造为
struct Exchanges {}
struct currency {}
struct rates {}
最佳答案
您的数据不是数组,而是字典。 要解析它,您可以使用:
let exchanges = try
JSONDecoder().decode(Exchanges.self, from: data)
如果你想将它转换为数组,那么将新的数组对象创建为:
let exchange: [Exchanges] = [exchanges]
关于json - Swift 4 JSON 解析(预期解码 Array<Any> 但发现字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031856/