预期对Array< Any>进行解码.但是找到了字典 [英] Expected to decode Array<Any> but found a dictionary instead

查看:93
本文介绍了预期对Array< Any>进行解码.但是找到了字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从返回数组的API中获取数据,但需要用具有子级别"的API替换它:

I was fetching data from an API returning an array but needed to replace it by an API that has "sub levels":

RAW:
    ETH:
        USD:
             TYPE:              "5"
             MARKET:            "CCCAGG"
             FROMSYMBOL:        "ETH"
             TOSYMBOL:          "USD"
             PRICE:             680.89
             CHANGEPCT24HOUR    :   -9.313816893529749

这是我的结构:

struct Ethereum: Codable {

    let percentChange24h: String
    let priceUSD: String

    private enum CodingKeys: String, CodingKey {
        case priceUSD = "PRICE", percentChange24h = "CHANGEPCT24HOUR"
    }
}

执行:

    func fetchEthereumInfo(completion: @escaping (Ethereum?, Error?) -> Void) {
    let url = URL(string: "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else { return }
        do {
            if let ethereumUSD = try JSONDecoder().decode([Ethereum].self, from: data).first {
                print(ethereumUSD)
                completion(ethereumUSD, nil)
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

控制台将显示typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

我真的无法弄清楚代码中要更新的内容或这种形式的API是什么

I can't really figure out what to update in my code or what this form of API is

推荐答案

首先,JSON不包含任何数组.读取JSON非常非常容易.只有2种(两种!)集合类型,数组[]和字典{}.如您所见,JSON字符串中根本没有方括号.

First of all the JSON does not contain any array. It's very very easy to read JSON. There are only 2 (two!) collection types, array [] and dictionary {}. As you can see there are no square brackets at all in the JSON string.

任何(子)词典{}都必须解码为自己的类型,因此应该是

Any (sub)dictionary {} has to be decoded to its own type, so it's supposed to be

struct Root : Decodable {
    private enum CodingKeys : String, CodingKey { case raw = "RAW" }
    let raw : RAW
}

struct RAW : Decodable {
    private enum CodingKeys : String, CodingKey { case eth = "ETH" }
    let eth : ETH
}

struct ETH : Decodable {
    private enum CodingKeys : String, CodingKey { case usd = "USD" }
    let usd : USD
}

struct USD : Decodable {

    private enum CodingKeys : String, CodingKey {
        case type = "TYPE"
        case market = "MARKET"
        case price = "PRICE"
        case percentChange24h = "CHANGEPCT24HOUR"
    }
    let type : String
    let market : String
    let price : Double
    let percentChange24h : Double
}

要解码JSON并打印percentChange24h,您必须编写

To decode the JSON and and print percentChange24h you have to write

 let result = try JSONDecoder().decode(Root.self, from: data)
 print("percentChange24h", result.raw.eth.usd.percentChange24h)

这篇关于预期对Array&lt; Any&gt;进行解码.但是找到了字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆