无法正确获取JSON数据

Abrcd18

我正在尝试从此服务https://coinmarketcap.com/api/获取加密数据,而Postman返回以下响应正文:

"status": {
    "timestamp": "2020-09-03T11:33:00.616Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 101,
    "credit_count": 1,
    "notice": null
},
"data": [
    {
        "id": 1,
        "name": "Bitcoin",
        "symbol": "BTC",
        "slug": "bitcoin",
        "num_market_pairs": 8938,
        "date_added": "2013-04-28T00:00:00.000Z",
        "tags": [
            "mineable",
            "pow",
            "sha-256",
            "store-of-value",
            "state-channels"
        ],
        "max_supply": 21000000,
        "circulating_supply": 18478475,
        "total_supply": 18478475,
        "platform": null,
        "cmc_rank": 1,
        "last_updated": "2020-09-03T11:31:33.000Z",
        "quote": {
            "USD": {
                "price": 11273.4407683,
                "volume_24h": 25364037841.8901,
                "percent_change_1h": -0.600125,
                "percent_change_24h": -2.18778,
                "percent_change_7d": -0.96201,
                "market_cap": 208315993401.01236,
                "last_updated": "2020-09-03T11:31:33.000Z"
            }
        }
    },

这是我的JSON结构。我收到以下错误。有什么事吗

valueNotFound(Swift.Double,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ data”,intValue:nil),CodingKeys(stringValue:“ quote”,intValue:nil)

struct Response: Decodable {
    var data: [CryptoData] 
}

struct CryptoData: Decodable {

var id: Int
var name: String
var symbol: String
var slug: String
var maxSupply: Int?
var totalSupply: QuantumValue
var rank: Int
var lastUpdated: String

var quote: QuoteDetails

enum CodingKeys: String, CodingKey {
    
    case id
    case name
    case symbol
    case slug
    case maxSupply = "max_supply"
    case totalSupply = "total_supply"
    case rank = "cmc_rank"
    case lastUpdated = "last_updated"
    case quote
}
}

struct QuoteDetails: Decodable {
     var USD: QuoteUSD
}

struct QuoteUSD: Decodable {

var price: Double
var dailyVolume: Double
var percentChangeIn1h: Double
var percentChangeIn24h: Double
var percentChangeIn7d: Double
var marketCap: Double
var lastUpdated: String

enum CodingKeys: String, CodingKey {
    case price
    case dailyVolume = "volume_24h"
    case percentChangeIn1h = "percent_change_1h"
    case percentChangeIn24h = "percent_change_24h"
    case percentChangeIn7d = "percent_change_7d"
    case marketCap = "market_cap"
    case lastUpdated = "last_updated"
}
}

我要提出的功能:

func loadData() {
    
    guard let url = URL(string: "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest") else {
        
        print("Wrong URL.")
        return
    }
    
    let finalURL = url
    var request = URLRequest(url: finalURL)
    request.addValue("c972ac08-519e-47e5-8cd8-23e6230289f3", forHTTPHeaderField: "X-CMC_PRO_API_KEY")
    
    let dataTask = URLSession.shared.dataTask(with: request) { (data, responce, error) in
        
        if let jsonData = data {
            
            do {
                
                let cryptoData = try JSONDecoder().decode(Response.self, from: jsonData)
                print(cryptoData)
            }
            
            catch {
                
                print(error)
            }
        }
    }
    dataTask.resume()
}
理查德广场

使用url / api键(应该从问题中删除),我发现您的数据模型存在两个问题。

首先...解析时生成的完整错误是:

valueNotFound(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 63", intValue: 63), CodingKeys(stringValue: "quote", intValue: nil), _JSONKey(stringValue: "USD", intValue: nil), CodingKeys(stringValue: "percent_change_7d", intValue: nil)], debugDescription: "Expected Double value but found null instead.", underlyingError: nil))

其中QuoteUSD一个的NULL值。为了对此进行解析,您percentChangeIn7d应该成为可选::var percentChangeIn7d: Double?

第二...

dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 90", intValue: 90), CodingKeys(stringValue: "max_supply", intValue: nil)], debugDescription: "Parsed JSON number <133248297.197> does not fit in Int.", underlyingError: nil))

这表明max_supply可能不是an Int,因此使aDouble可能就足够了:var maxSupply: Double?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章