簡體   English   中英

為什么我不能使用可編碼解碼這個json數據?

[英]Why can't I decode this json data using codable?

我正在嘗試解碼一個看起來像這樣的json:

[
  {
"id": "bitcoin",
"symbol": "btc",
"name": "Bitcoin",
"image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1510040391",
"current_price": 6419.05058467597,
"market_cap": 110769065096.2,
"market_cap_rank": 1,
"total_volume": 7134416215.16392,
"high_24h": 6999.30273116437,
"low_24h": 6265.34668792378,
"price_change_24h": "-580.08447091048",
"price_change_percentage_24h": "-8.28794510040892",
"market_cap_change_24h": "-10080785067.733",
"market_cap_change_percentage_24h": "-8.34157845794463",
"circulating_supply": "17252725.0",
"ath": 19665.3949272416,
"ath_change_percentage": -67.3505163492418,
"ath_date": "2017-12-16T00:00:00.000Z",
"roi": null,
"last_updated": "2018-09-06T16:03:23.307Z"
  },
  {
"id": "ethereum",
"symbol": "eth",
"name": "Ethereum",
"image": "https://assets.coingecko.com/coins/images/279/large/ethereum.png?1510040267",
"current_price": 226.482375502941,
"market_cap": 23071362046.6026,
"market_cap_rank": 2,
"total_volume": 3957109077.73956,
"high_24h": 256.816443923474,
"low_24h": 215.415109745597,
"price_change_24h": "-30.246516631482",
"price_change_percentage_24h": "-11.7815008587522",
"market_cap_change_24h": "-3068068475.6338",
"market_cap_change_percentage_24h": "-11.7373194990757",
"circulating_supply": "101792652.9678",
"ath": 1448.1800861342,
"ath_change_percentage": -84.320027361102,
"ath_date": "2018-01-13T00:00:00.000Z",
"roi": {
  "times": 46.14410145864465,
  "currency": "btc",
  "percentage": 4614.410145864465
},
"last_updated": "2018-09-06T16:03:23.331Z"
  },

我需要這些數據是可訪問的,以便在需要時可以輕松訪問比特幣,以太幣或列表中任何一個的價格,圖像網址等。

這就是我試圖這樣做的方式:

import UIKit
import PlaygroundSupport
import Foundation

class MyViewController : UIViewController {
    struct Coins: Decodable {

    let id: String
    let name: String
    let current_price: Double
} // I have also tried: let id: [String] etc.

override func loadView() {
    let view = UIView()
    view.backgroundColor = .white

    let label = UILabel()
    label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
    label.text = "Hello World!"
    label.textColor = .black

    view.addSubview(label)
    self.view = view

    let urlJSON = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=btc"

    guard let url = URL(string: urlJSON) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in

        guard let data = data else { return }

        //let dataAsString = String(data: data, encoding: .utf8)

        //print(dataAsString)

        do {
            let coins = try JSONDecoder().decode(Coins.self, from: data)
            print(coins.id)

        } catch let jsonErr {
            print("error serializing json")
            print()
        }

        }.resume()
}

但我只是得到了“錯誤序列化json”,雖然如果我將json打印為String,我會獲得完整的json以便urlsession正常工作。 我究竟做錯了什么?

你錯了..請這樣做

 let coins = try JSONDecoder().decode([Coins].self, from: data)

當您獲取數組時,您需要解析struct數組

struct Coins: Decodable {

        let id: String?
        let name: String?
        let current_price: Double?
    }

您的JSON是一個數組,因此您應該使用

JSONDecoder().decode([Coins].self, from: data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM