Arrays 如何在Swift中解码具有未知密钥的JSON响应?

Arrays 如何在Swift中解码具有未知密钥的JSON响应?,arrays,json,swift,Arrays,Json,Swift,我想分开,这样每一行都是数组中自己的字符串 我正在制作一个应用程序,获取所选货币的价格。因此,如果有人想要AUD,那么它将获得数组中的2字符串,然后显示最后一个标记中的价格 我目前正在下载json func reloadJson(){ if globalVariables.currencySelected == "" { globalVariables.currencySelected = globalVariables.currencySelected + "AUD"

我想分开,这样每一行都是数组中自己的字符串

我正在制作一个应用程序,获取所选货币的价格。因此,如果有人想要AUD,那么它将获得数组中的2字符串,然后显示最后一个标记中的价格

我目前正在下载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)
这只是我目前拥有的东西的复制和粘贴,它的格式不完全正确


谢谢

您应该看看Swift4可编码协议

为货币字典值创建一个结构,该结构符合Codable,并具有相应的属性:

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数据,您需要使用
jsondeconder
将自定义值传递给字典
[String:Currency]
作为要解码的类型:

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()

这会打印出来

1500万美元:11694.03

美元-上次:11694.03

美元-买入价:11695.01

美元-卖出价:11693.04

美元-符号:$


如果您通过拆分字符串来解析JSON,那么您就做错了。查找
JSONDecoder
查看SwiftOK谢谢,我已经更改了。你知道我想做什么吗?High Sierra上的Xcode 9.2