预期解码 Array<Any>但找到了一本字典

编程入门 行业动态 更新时间:2024-10-20 16:12:34
本文介绍了预期解码 Array<Any>但找到了一本字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我从返回数组的 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/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

我真的不知道要在我的代码中更新什么或这种形式的 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<Any>但找到了一本字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 16:29:04,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:一本   字典   找到了   Array   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!