如何从JSON Object Swift 4检索值 [英] How to retrieve a value from JSON Object Swift 4
问题描述
我正在尝试使用Swift 4的Codable解码JSON对象:
I am trying to decode JSON object using Codable with Swift 4:
{
USD: {
"15m": 9977.49,
last: 9977.49,
buy: 9979.36,
sell: 9975.62,
symbol: "$"
},
AUD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
},
TBD: {
"15m": 13181.69,
last: 13181.69,
buy: 13184.16,
sell: 13179.22,
symbol: "$"
}
}
到目前为止,这是我对对象模型所做的:
This is what I've done so far with a model of an object:
struct Currency: Codable {
let fifteenMin: Double?
let last: Double?
let buy: Double
let sell: Double
let symbol: String
enum CodingKeys: String, CodingKey {
case fifteenMin = "15m"
case last
case buy
case sell
case symbol
}
}
这就是我解码的方式:
var currencyName = [String]()
var currenciesArray = [Currency]()
func fetchCurrencyData() {
guard let urlString = API.RateURL.absoluteString else { return }
guard let url = URL(string: urlString) else { return }
let jsonData = try! Data(contentsOf: url)
let decoder = JSONDecoder()
do {
let currenciesData = try decoder.decode([String: Currency].self, from: jsonData)
for currency in currenciesData {
self.currencyName.append(currency.key)
self.currenciesArray.append(currency.value)
}
} catch let err {
print(err.localizedDescription)
}
}
因此,当我想用该数据填充tableView中的行时,我使用"for循环"并在一个数组中附加"USD","AUD"等,并在另一个数组中附加Currency对象.
So when I want to populate rows in tableView with that Data I use "for loop" and append "USD", "AUD" and so on in one array and Currency object in another array.
获取数据和填充Currency对象的更好方法是什么.因为我很确定,我认为将JSON的相同对象附加到两个单独的数组中并附加到这两个数组中并不是很好的做法.
What is the better way of fetching data and populating Currency object. Cuz I am pretty sure that fetching and appending the same object of JSON into two separate arrays isn't good practice I assume.
如果我的问题不清楚,我可以更详细地说明我想要实现的目标.
If my question isn't clear I can explain in more details what I would like to achieve.
谢谢.
推荐答案
维护多个数组非常烦人(而且容易出错).我建议在结构中包含 name .
It's quite annoying (and error-prone) to maintain multiple arrays. I recommend to include the name in the struct.
在Currency
var name = ""
解码JSON后,对密钥进行排序,获取相应的值并将name
设置为key
After decoding the JSON sort the keys, get the corresponding value and set the name
to the key
var currenciesArray = [Currency]()
let currencies = try decoder.decode([String: Currency].self, from: jsonData)
for key in currencies.keys.sorted() {
var currency = currencies[key]!
currency.name = key
currenciesArray.append(currency)
}
print(currenciesArray)
这篇关于如何从JSON Object Swift 4检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!