【问题标题】:Why can't I decode this json data using codable?为什么我不能使用可编码解码这个 json 数据?
【发布时间】:2019-02-11 23:09:30
【问题描述】:

我正在尝试解码如下所示的 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 打印为字符串,我会得到完整的 json,所以 urlsession 工作。 我做错了什么?

【问题讨论】:

  • print("error serializing json"); print() 这没用。取而代之的是 print("error serializing json: \(jsonError)") 这应该会给你关于哪里出了问题的真正有趣的信息。就像您的 JSON 是顶级数组一样。

标签: json swift xcode decodable


【解决方案1】:

你做错了..请这样做

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

当你得到数组时,你需要解析结构数组

struct Coins: Decodable {

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

【讨论】:

  • 我还需要更改结构吗?这似乎工作了一次,但由于某种原因我无法再次获得该结果,但我仍然收到错误。 json err 也返回 nil 但响应有效。
  • 是的,你需要在最后添加可选因为可能在响应值将为零所以请检查我更新的答案
  • @PeterRuppert: 请给我看你的 jsonErr , print(jsonErr)
  • 好吧,这是因为我在结构中添加了一个新的 let: let current_price: Double, error serializing json: valueNotFound(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 1918", intValue: 1918), CodingKeys(stringValue: "current_price", intValue: nil)], debugDescription: "预期的 Double 值,但发现为 null。",underlyingError: nil))
  • 您不需要将结构的所有属性都设为可选。仅当 JSON 中可能缺少特定值时才将属性设为可选。
【解决方案2】:

你的 JSON 是一个数组,所以你应该使用

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

【讨论】:

  • 这给了我“无法使用类型为 '([CGPrices.Coins.Type], from: Data)' 的参数列表调用 'decode'”
  • @rmaddy 糟糕,我很着急。感谢指正
猜你喜欢
  • 2019-11-28
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多