我正在尝试使用swift 4:
来解码JSON对象{
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: "$"
}
}
这是我到目前为止使用对象模型所做的:
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)
}
}
因此,当我想使用" for for loop"的数据填充桌上的行时,并在另一个数组中的一个数组和货币对象中附加" for for loop"," usd"," aud"等。
获取数据和填充货币对象的更好方法是什么?因为我很确定,将JSON的相同对象添加到两个单独的阵列中,我认为,我认为,我认为json的对象并不是一个好练习。
如果我的问题不清楚,我可以在更多详细信息中解释我想实现的目标。
谢谢。
保持多个数组非常烦人(容易出错)。我建议将名称包括在结构中。
在Currency
var name = ""
解码JSON排序键后,获取相应的值并将name
设置为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)
货币名称不应该在货币对象内吗?那将容易得多。
但是,如果您必须使用该格式,则可以创建一个元组或字典。
var currenciesArray = [(String, Currency)]()
然后以这样的添加:
for currency in currenciesData {
currenciesArray.append((currency.key, currency.value))
}
P.S。:您需要在JSON内的字符串值上添加引号("),否则它将无效。
****添加了*****
下面的代码将编码和解码与您提到的相似的JSON:
struct Price: 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
}
}
struct Currencies: Codable {
var USD: Price?
var JPY: Price?
var EUR: Price?
var AUD: Price?
}
let usdPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "$")
let jpyPrice = Price(fifteenMin: 10, last: 11, buy: 12, sell: 13, symbol: "¥")
var currencies = Currencies()
currencies.USD = usdPrice
// Encode data
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(currencies)
let jsonString = String(data: jsonData, encoding: .utf8)
print("JSON String : " + jsonString!)
do {
// Decode data to object
let jsonDecoder = JSONDecoder()
let currencies = try jsonDecoder.decode(Currencies.self, from: jsonData)
print("USD: (currencies.USD)")
print("JPY: (currencies.JPY)")
}
catch {
}
}
catch {
}