如何在 Swift 中使用未知密钥解码 JSON 响应? [英] How can I decode a JSON response with an unknown key in Swift?
问题描述
我想拆分 https://blockchain.info/ticker 以便每一行都是自己的数组中的字符串.
Im wanting to split up https://blockchain.info/ticker so that each line is its own string in an array.
我正在制作一个可以获取所选货币价格的应用程序.因此,如果有人想要 AUD,那么它将获取数组中的第 2 个字符串,然后显示最后一个标签中的价格.
Im making an app that get the price of the selected currency. So if someone wants AUD then it will get the 2 string in the array and then show the price which is in the last tag.
我目前只是让它下载 json..
I currently just have it downloading the json..
func reloadJson(){
if globalVariables.currencySelected == "" {
globalVariables.currencySelected = globalVariables.currencySelected + "AUD"
}
print(globalVariables.currencySelected)
if let blockchainTickerURL = URL(string: "https://blockchain.info/ticker") {
let request = NSMutableURLRequest(url: blockchainTickerURL)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
var message = ""
if error != nil {
print("error")
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
这只是我目前拥有的内容的复制和粘贴,格式不完全正确.
Thats just a copy and paste of what I currently have, its not exactly formatted right.
谢谢
推荐答案
你应该看看 Swift4 Codable 协议.
You should take a look at Swift4 Codable protocol.
为符合 Codable 的货币字典值创建一个具有相应属性的结构:
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
}
}
要解码您的 JSON 数据,您需要使用 JSONDecoder
传递带有自定义值的字典 [String: Currency]
作为要解码的类型:
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
美元 - 1500 万美元:11694.03
USD - 15m: 11694.03
美元 - 最新:11694.03
USD - last: 11694.03
美元 - 买入:11695.01
USD - buy: 11695.01
美元 - 卖出:11693.04
USD - sell: 11693.04
USD - 符号:$
这篇关于如何在 Swift 中使用未知密钥解码 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!