How can I decode a JSON response with an unknown key in Swift?

前端 未结 1 590
猫巷女王i
猫巷女王i 2020-12-12 07:05

Im wanting to split up https://blockchain.info/ticker so that each line is its own string in an array.

Im making an app that get the price of the selected currency.

相关标签:
1条回答
  • 2020-12-12 07:48

    You should take a look at Swift4 Codable protocol.

    Create a structure for the currency dictionary values that conforms to Codable with the corresponding properties:

    struct Currency: Codable {
        let fifteenM: Double
        let last: Double
        let buy: Double
        let sell: Double
        let symbol: String
        private enum CodingKeys: String, CodingKey {
            case fifteenM = "15m", last, buy, sell, symbol
        }
    }
    

    To decode your JSON data you need to use JSONDecoder passing the dictionary with custom values [String: Currency] as the type to be decoded:

    let url = URL(string: "https://blockchain.info/ticker")!
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data else { return }
        do {
            let currencies = try JSONDecoder().decode([String: Currency].self, from: data)
            if let usd = currencies["USD"] {
                print("USD - 15m:", usd.fifteenM)
                print("USD - last:", usd.last)
                print("USD - buy:", usd.buy)
                print("USD - sell:", usd.sell)
                print("USD - symbol:", usd.symbol)
            }
        } catch { print(error) }
    
    }.resume()
    

    This will print

    USD - 15m: 11694.03

    USD - last: 11694.03

    USD - buy: 11695.01

    USD - sell: 11693.04

    USD - symbol: $

    0 讨论(0)
提交回复
热议问题