json - 从数组中获取数据以响应 Swift
问题描述
我正在访问一个 API,响应显示如下,
"responseBody": {
"data": [
"{\"AED_USD\":0.272255,\"USD_AED\":3.67305}"
]
}
我很困惑如何从这个数组数据中取出 AED_USD 和 USD_AED 的值。我尝试将所有响应放入数组中,并尝试从索引库中获取值,但不起作用。我怎样才能获得价值?我的代码是这样的,
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
self.exchangeRateArray.append(ExchangeRateCurrency(JSON:userData)!)
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
解决方案
您的数据是字符串形式,将字符串更改为 JSON NSditonary。尝试像这样转换
let str = "{\"AED_USD\":0.272257,\"USD_AED\":3.673001}"
if let data = str.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
// 在你的代码中。
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
print(userData)
// if you get string from userData
if let data = userData.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
//self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}
推荐阅读
- r - 带有多个标签ggplot2的条形图
- ruby - 用户保存的数据使复选框的初始值
- javascript - 如何使用 axios 从 React-Native-Image-Picker 上传图像?
- sockets - boost::asio,async_receive_from 超时,当使用单个 Udp 套接字侦听多个端点时?
- python - PyDrive上传速度太慢
- javascript - 如何摆脱 SVG 图像上的边框?
- terraform - terraform init 期间的“变量可能不会在此处使用”
- common-lisp - 如何在 Lisp 中确定文件类型
- python - Python动态函数参数
- kotest - 一遍又一遍地运行相同的kotest测试的简单方法?