【发布时间】:2026-02-17 09:55:01
【问题描述】:
我似乎无法正确解码此 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 {}
【问题讨论】:
-
[Exchanges].self你告诉你的JSONDecoder它必须解码Exchanges对象的数组,而实际上它是一个数组。至少删除方括号。 -
之前没有看到这条评论。非常感谢您的帮助