简体   繁体   English

为什么我不能使用可编码解码这个json数据?

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

I am trying to decode a json that looks like this: 我正在尝试解码一个看起来像这样的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"
  },

I need this data to be accessible so that it is easy to access the prices, image url etc of bitcoin,ethereum or any in the list when needed. 我需要这些数据是可访问的,以便在需要时可以轻松访问比特币,以太币或列表中任何一个的价格,图像网址等。

This is how I am trying to do it: 这就是我试图这样做的方式:

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()
}

But I just get the "Error serializing json", although if I print the json as String, I get the full json so the urlsession works. 但我只是得到了“错误序列化json”,虽然如果我将json打印为String,我会获得完整的json以便urlsession正常工作。 What am I doing wrong? 我究竟做错了什么?

You are doiing wrong.. please do like this 你错了..请这样做

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

As you are getting array so you need to parse array of struct 当您获取数组时,您需要解析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