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

标签 json swift xcode decodable

我正在尝试解码如下所示的 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"
  },

我需要这些数据可以访问,以便在需要时可以轻松访问比特币、以太坊或列表中任何内容的价格、图像 url 等。

这就是我尝试这样做的方式:

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 打印为字符串,我会得到完整的 json,因此 urlsession 可以工作。 我做错了什么?

最佳答案

你做错了..请这样做

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

因为你正在获取数组所以你需要解析结构数组

struct Coins: Decodable {

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

关于json - 为什么我不能使用 codable 解码这个 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52208267/

相关文章:

javascript - 第 26 行出现意外标记 },但第 26 行 ajax 调用上没有 }

ios - 如何更改 AVPlayer 中播放音频的速度?

ios - Swift和API:解码JSON树

ios - 通过 Parse 查询更新 UITableView 的策略

iphone - 如何在 Sprite 生成器中添加单独的iPad和iPhone图像 - Cocos2d 3.2

swift - healthStore.requestAuthorization() 导致 Apple Watch 应用程序崩溃

javascript - 如何将帖子分享到 linkedin

node.js - AJV 使用 JSONPath 字符串验证架构

ios - 如何使用 SDK 版本 4.x 构建 MonoTouch 应用程序(不针对当前 sdk 的早期版本)

javascript - 如何导出 JSON 文件中的对象数组,然后使用 es6 导入