【问题标题】:Which structure to use to parse data in JSON?使用哪种结构来解析 JSON 中的数据?
【发布时间】:2020-07-09 06:18:08
【问题描述】:

我对使用 JSON 非常陌生,我正在尝试找出使用 swift 将以下数据解析到我的应用程序的最佳解决方案。到目前为止,我已经成功地创建了结构来将数据解析到我的应用程序中,但是使用这个 API 我有点困惑。

我正在寻找的值的路径返回:0.price

在我正在处理的 JSON 下方——我需要一个结构来检索“价格”值——我知道它是一个嵌套在数组中的快速字典,但我真的不知道如何创建这个结构来获取0.价格价值。

[
    {
        "id": "BTC",
        "currency": "BTC",
        "symbol": "BTC",
        "name": "Bitcoin",
        "logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg",
        "price": "9397.86203481",
        "price_date": "2020-07-09T00:00:00Z",
        "price_timestamp": "2020-07-09T05:10:00Z",
        "circulating_supply": "18427462",
        "max_supply": "21000000",
        "market_cap": "173178745528",
        "rank": "1",
        "high": "19343.01808710",
        "high_timestamp": "2017-12-16T00:00:00Z",
        "1d": {
            "volume": "19780482959.23",
            "price_change": "55.47211721",
            "price_change_pct": "0.0059",
            "volume_change": "1974758604.83",
            "volume_change_pct": "0.1109",
            "market_cap_change": "1030908096.99",
            "market_cap_change_pct": "0.0060"
        },
        "30d": {
            "volume": "663105718213.57",
            "price_change": "-472.08068928",
            "price_change_pct": "-0.0478",
            "volume_change": "-451402235448.26",
            "volume_change_pct": "-0.4050",
            "market_cap_change": "-8416909381.05",
            "market_cap_change_pct": "-0.0463"
        }
    }
]

谢谢,

最大

【问题讨论】:

  • 您一定尝试过或研究过一些东西,请向我们展示您的代码。

标签: json swift xcode parsing networking


【解决方案1】:

使用Codable解析上述JSON响应

Codable模特:

Option-1:如果要解析所有数据

struct Response: Codable {
    let id, currency, symbol, name: String
    let logoUrl: String
    let price: String
    let priceDate, priceTimestamp: String
    let circulatingSupply, maxSupply, marketCap, rank: String
    let high: String
    let highTimestamp: String
    let the1D, the30D: The1_D

    enum CodingKeys: String, CodingKey {
        case id, currency, symbol, name, logoUrl, price, priceDate, priceTimestamp, circulatingSupply, maxSupply, marketCap, rank, high, highTimestamp
        case the1D = "1d"
        case the30D = "30d"
    }
}

struct The1_D: Codable {
    let volume, priceChange, priceChangePct, volumeChange: String
    let volumeChangePct, marketCapChange, marketCapChangePct: String

}

选项 2:如果您只需要 price 值而忽略其他所有内容,

struct Response: Codable {
    let price: String
}

解析 JSON data 像这样,

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let response = try decoder.decode([Response].self, from: data)
    let price = response.first?.price //Get the value of price here..
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多