Swift 4 JSON 解析(预期解码 Array,但找到了字典)
问题描述:
我似乎无法获得正确的结构来解码此 API.都是字典 ({...}) 但我的代码一直试图将其解构为数组.
I can't seem to get the structure right to decode this API. It's all dictionaries ({...}) yet my code keeps trying to deconstruct it as an array.
错误代码:
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=比特币
Link to API for parsing: 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 {}
答
你的数据不是数组,它是字典.要解析它,您可以使用:
Your Data is not Array, it is Dictionary. To Parse it, you can use:
let exchanges = try
JSONDecoder().decode(Exchanges.self, from: data)
如果要将其转换为数组,则将数组的新对象创建为:
If you want to convert it in array then make new Object of array as:
let exchange: [Exchanges] = [exchanges]