在 Swift 中解析 JSON 4(初学者编码器)

Parsing JSON in Swift 4 (Beginner coder)

如果这是一个愚蠢的问题,请提前道歉。我真的很陌生。

所以我正在尝试制作一个简单的应用程序来显示用户选择的特定货币的当前比特币价格。

首先我准备 URL:

let baseURL = "https://api.coindesk.com/v1/bpi/currentprice/"
let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"]
    var finalURL = ""

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        finalURL = baseURL + currencyArray[row]
        coinSelected = currencyArray[row]
        getBitcoinData(url: finalURL)
    }

然后我得到 JSON 数据。

Alamofire.request(url, method: .get)
            .responseJSON { response in
                if response.result.isSuccess {
                    let bitcoinJSON = JSON(response.result.value!)
                    print bitcoinJSON

到目前为止一切顺利,我得到了我的 JSON 数据并且打印正确。

{
    "time": {
        "updated": "Apr 17, 2020 08:39:00 UTC",
        "updatedISO": "2020-04-17T08:39:00+00:00",
        "updateduk": "Apr 17, 2020 at 09:39 BST"
    },
    "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
    "bpi": {
        "USD": {
            "code": "USD",
            "rate": "7,074.9583",
            "description": "United States Dollar",
            "rate_float": 7074.9583
        },
        "GBP": {
            "code": "GBP",
            "rate": "5,687.3185",
            "description": "British Pound Sterling",
            "rate_float": 5687.3185
        }
    }
}

我接下来要做的是获取英镑汇率。 (不知何故美元汇率总是显示在我选择的货币之前)

我尝试做的是:

 func updateBitcoinData(json : JSON) {

        let bitcoinRATE = json ["bpi"][1]["rate"]
        print(bitcoinVALUE)

    }

但它总是 return 零...

您不应访问带有 [1] 等索引的字典。字典中的元素没有保证的顺序。今天,元素顺序是 USD、GBP,但明天可能是 GBP、USD。它们在技术上仍然是同一本词典。因此,您应该始终使用字典的 Key 来访问它。例如["GBP"].

从问题的上下文看,你想做的似乎是获取用户选择的货币,但是API总是给出美元的汇率以供参考。

didSelectRow 中,您将所选货币分配给 coinSelected,因此您可以只使用 coinSelected 作为键:

if let bitcoinRATE = json["bpi"][coinSelected]["rate"].string {
    // success!
} else {
    // the user has changed the selection before the response is received 
}

如果只有两种货币,只需找到不是 USD

first
let currencies = bitcoinJSON["bpi"]
if let notUSDCurrency = currencies.dictionary?.keys.first(where: { [=10=] != "USD" }) {
    let rate = currencies[notUSDCurrency]["rate"].stringValue
    print( "Rate of \(notUSDCurrency):", rate)
}