Swift 4 JSON解析(预计解码数组<any>但是找到了一个字典)

时间:2018-04-25 21:50:23

标签: json swift parsing swift4

我似乎无法正确解析此API的结构。它是所有字典({...})但我的代码一直试图将其解构为数组。

错误代码:

.items()

链接到API以进行解析: https://api.coinbase.com/v2/exchange-rates?currency=BTC

代码:

 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

结构:

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
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

您的数据不是数组,而是字典。 要解析它,你可以使用:

let exchanges = try
                JSONDecoder().decode(Exchanges.self, from: data)

如果要在数组中转换它,则将新的数组对象设为:

let exchange: [Exchanges] = [exchanges]