gpt4 book ai didi

json - 想查看json元数据

转载 作者:行者123 更新时间:2023-11-28 14:27:19 25 4
gpt4 key购买 nike

我正在尝试使用适用于 iOS 的 Alpha Vantage API 构建一个显示货币汇率的应用程序。我已经构建了函数,但无法弄清楚如何访问确切的 json 值,即“5. 汇率”。

下面是一些代码和 json 数据,以帮助更好地解释:

构建的 URL:

func USDtoEUR(_ completionHandler: @escaping (_ success: Bool, _ quotes: [String:AnyObject]?, _ error: String?) -> Void) {

let urlString = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=NP3M8LL62YJDO0YX"
let session = URLSession.shared
let url = URL(string: urlString)!

let request = URLRequest(url: url)
let task = session.dataTask(with: request, completionHandler: { data, response, error in
if error != nil {
completionHandler(false, nil, error!.localizedDescription)
}
else {
do {
let result = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
if let dictionary = result["Realtime Currency Exchange Rate"] as? [String:AnyObject]! {
completionHandler(true, dictionary, nil)
}
else {
completionHandler(false, nil, nil)
}
} catch {
completionHandler(false, nil, "Unable to process retrieved data.")
}
}

})
task.resume()

}

View Controller 中的引号

func usdQUotesRequest() {

USDClient().USDtoEUR() { success, newQuote, error in

if success {
self.usdtoeurquote = newQuote
DispatchQueue.main.async {
self.stopActivityIndicator()
self.Refresh.isEnabled = true
}

} else {
DispatchQueue.main.async {
self.displayAlert("Unable to Retrieve Latest Conversion Rates", message: "\(error!)")
self.stopActivityIndicator()
self.Refresh.isEnabled = true

}
}
}

//触摸美元按钮后显示的报价:

@IBAction func usdConversions(_ sender: Any) {

self.displayAlert("Alert!", message: "USD Selected")

let usdVal = (outputCurrency1.text! as NSString).floatValue

let euroValue = usdVal * (usdtoeurquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", euroValue)

let gbpVal = usdVal * (usdtogbpquote["5. Exchange Rate"] as! Float)
outputCurrency3.text = String(format: "%.2f", gbpVal)

let cnyVal = usdVal * (usdtocnyquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", cnyVal)

let cadVal = usdVal * (usdtocadquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", cadVal)

let inrVal = usdVal * (usdtoinrquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", inrVal)

let sekVal = usdVal * (usdtosekquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", sekVal)

let rubVal = usdVal * (usdtorubquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", rubVal)

let nzdVal = usdVal * (usdtonzdquote["5. Exchange Rate"] as! Float)
outputCurrency2.text = String(format: "%.2f", nzdVal)

}

原始 JSON 数据:The json data on the webpage

最佳答案

主要错误是键 5 的值。 Exchange RateString 而不是 Float 并且在强制解包时代码会可靠地崩溃。

在 Swift 4 中,Decodable 协议(protocol)比字典方便得多。

创建两个结构。 ExchangeRate 结构包含计算属性 floatRate 以返回 Float

struct Root : Decodable {
let exchangeRate : ExchangeRate
private enum CodingKeys: String, CodingKey { case exchangeRate = "Realtime Currency Exchange Rate" }
}

struct ExchangeRate : Decodable {

let fromCode, fromName, toCode, toName, rate : String
let lastRefreshed, timeZone : String

private enum CodingKeys: String, CodingKey {
case fromCode = "1. From_Currency Code"
case fromName = "2. From_Currency Name"
case toCode = "3. To_Currency Code"
case toName = "4. To_Currency Name"
case rate = "5. Exchange Rate"
case lastRefreshed = "6. Last Refreshed"
case timeZone = "7. Time Zone"
}

var floatRate : Float {
return Float(rate) ?? 0.0
}
}

然后通过将 fromto 货币作为参数传递,使下载功能更加通用。此版本使用 JSONDecoder 并返回 ExchangeRate 实例或 Error

func downloadRate(from: String, to: String, completionHandler: @escaping (ExchangeRate?, Error?) -> Void) {

let urlString = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=\(from)&to_currency=\(to)&apikey=NP3M8LL62YJDO0YX"
let task = URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { data, response, error in
if error != nil {
completionHandler(nil, error!)
} else {
do {
let result = try JSONDecoder().decode(Root.self, from: data!)
completionHandler(result.exchangeRate, nil)
} catch {
completionHandler(nil, error)
}
}
})
task.resume()
}

并使用它

func usdQUotesRequest() {

USDClient().downloadRate(from:"USD", to: "EUR") { exchangeRate, error in

if let exchangeRate = exchangeRate {
self.usdtoeurquote = exchangeRate.floatRate
DispatchQueue.main.async {
self.stopActivityIndicator()
self.Refresh.isEnabled = true
}
} else {
DispatchQueue.main.async {
self.displayAlert("Unable to Retrieve Latest Conversion Rates", message: "\(error!)")
self.stopActivityIndicator()
self.Refresh.isEnabled = true
}
}
}

关于json - 想查看json元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51467195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com