我正在尝试解码如下所示的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可以工作。 我在做什么错了?
答案 0 :(得分:2)
您做错了..请这样做
let coins = try JSONDecoder().decode([Coins].self, from: data)
在获取数组时,需要解析struct数组
struct Coins: Decodable {
let id: String?
let name: String?
let current_price: Double?
}
答案 1 :(得分:1)
您的JSON是一个数组,因此您应该使用
JSONDecoder().decode([Coins].self, from: data)