Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 希望解码Array但是找到了一本字典大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我从返回数组的API中获取数据,但需要用具有“子级别”的API替换它: RAW: ETH: USD: TYPE: "5" MARKET: "CCCAGG" FROMSymBOL: "ETH" TOSymBOL:
我从返回数组的API中获取数据,但需要用具有“子级别”的API替换它:
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:“预期解码数组< Any>但是找到了一个字典.”,underlyingError:nil))

我无法确定我的代码中要更新的内容或这种形式的API是什么

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

任何(子)字典{}必须被解码为它自己的类型,所以它应该是

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,您必须编写

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

大佬总结

以上是大佬教程为你收集整理的swift – 希望解码Array但是找到了一本字典全部内容,希望文章能够帮你解决swift – 希望解码Array但是找到了一本字典所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。