【发布时间】:2020-10-13 23:43:11
【问题描述】:
我正在从在线货币服务中提取货币价值。
在获得所有货币的 json 数组后,我选择 2 种货币进行比较。
[{
"symbol": "$",
"name": "US Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "USD",
"name_plural": "US dollars"
}, {
"symbol": "CA$",
"name": "Canadian Dollar",
"symbol_native": "$",
"decimal_digits": 2,
"rounding": 0,
"code": "CAD",
"name_plural": "Canadian dollars"
}]
我创建一个查询并将其发送回我的服务。
查询:
let URLString: String = finalURLPart1 + finalURLPart2 + finalURLPart3 + ""
//print(#function, "URLString: ", URLString)
var request = URLRequest(url: URL(string: URLString)!, timeoutInterval: Double.infinity)
//print(#function, "request: ", request)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertController.Style.alert)
let okButton = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
} else {
// 2- Getting the response (Data)
if data != nil {
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any>
//Async
print(jsonResponse)
DispatchQueue.main.async {
if let rates = jsonResponse["rates"] as? [String : Any] {
for convertedValue in rates.values {
print("convertedValue: ", convertedValue)
print("Type: ", type(of: convertedValue))
}
}
}
} catch {
print("Error")
}
}
}
}
// 3- Process the data (Parsing: or JSON Serialization)
task.resume() // starting the task
//semaphore.wait()
}
我拿回来了:
["base": BAM, "date": 2020-10-13 22:18:00+00, "rates": {
BDT = "51.11942821250704";
}]
for convertedValue in rates.values {
print("convertedValue: ", convertedValue)
print("Type: ", type(of: convertedValue))
}
输出是:
convertedValue: 51.11942821250704
Type: __NSCFString
如何获得convertedValue的浮点值?
【问题讨论】:
-
请编辑您的问题并发布收到的 JSON 字符串并正确格式化您的帖子
-
会的。感谢格式化..
-
返回的值不是有效的json
标签: arrays json swift dictionary