我想用 JSON 数据填充我拥有的数组。我正在使用 SwiftyJSON 和 Alamofire。我是解析 JSON 的新手,因此对于我的无知,我深表歉意。下面的 URL 是我在 getAllTimeAverage() 中插入的 URL。任何帮助都是极好的!!谢谢!
这是 JSON 数据https://apiv2.bitcoinaverage.com/indices/global/history/BTCILS?period=alltime&format=json
这是我要填充的数组
var allTimeAverages: [Any] = []
这些是我的职能。我在 cellForRowAt: 中调用它们,当我打印 allTimeAverages.count 时,我返回零。
func getAllTimeAverage(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the Bitcoin Data")
let bitcointJSON : JSON = [JSON(response.result.value!)]
self.updateAverageAllTime(json: bitcointJSON)
} else {
print("Error: \(String(describing: response.result.error))")
self.price = "Connection Issues"
}
}
}
func updateAverageAllTime(json: JSON) {
if let allTimeAverage = json["average"].dictionaryObject {
self.allTimeAverages.append(allTimeAverage)
}
}
func getBitcoinData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the Bitcoin Data")
let bitcointJSON : JSON = JSON(response.result.value!)
self.updateBitcoinData(json: bitcointJSON)
} else {
print("Error: \(String(describing: response.result.error))")
self.price = "Connection Issues"
}
}
}
以下是如何完成此操作的示例(我从您共享的 JSON API 中获取了一些值):
let jsonString = "[{\"high\": 23043.41,\"open\": 21494.60,\"low\": 21338.34,\"average\": 21668.01,\"time\": \"2018-06-29 00:00:00\",\"volume\": 102148.30132998565},{\"high\": 22488.75,\"open\": 22405.51,\"low\": 21380.97,\"average\": 22241.29,\"time\": \"2018-06-28 00:00:00\",\"volume\": 69383.44795111718},{\"high\": 22491.85,\"open\": 22169.36,\"low\": 21940.47,\"average\": 22224.29,\"time\": \"2018-06-27 00:00:00\",\"volume\": 69884.07809550199},{\"high\": 22707.46,\"open\": 22635.32,\"low\": 22004.29,\"average\": 22480.86,\"time\": \"2018-06-26 00:00:00\",\"volume\": 71611.8914173987}]";
if let jsonData = jsonString.data(using: .utf8, allowLossyConversion: false) {
let json = JSON(data: jsonData)
let jsonArray = json.arrayValue
let averagesArray = jsonArray.map{ $0["average"].doubleValue}
let highArray = jsonArray.map{ $0["high"].doubleValue}
let lowArray = jsonArray.map{ $0["low"].doubleValue}
let volumeArray = jsonArray.map{ $0["volume"].doubleValue}
let openArray = jsonArray.map{ $0["open"].doubleValue}
}
根据上述内容使您的解决方案起作用:在以下行中,删除 [],因为您已经从 API 获取了一个数组。
let bitcoinJSON : JSON = [JSON(response.result.value!)]
所以上面的行将变成
let bitcoinJSON : JSON = JSON(response.result.value!)
现在,您可以像我一样获取数组值:
let jsonArray = bitcoinJSON.arrayValue
现在您可以使用其余的代码(下面重复):
let averagesArray = jsonArray.map{ $0["average"].doubleValue}
let highArray = jsonArray.map{ $0["high"].doubleValue}
let lowArray = jsonArray.map{ $0["low"].doubleValue}
let volumeArray = jsonArray.map{ $0["volume"].doubleValue}
let openArray = jsonArray.map{ $0["open"].doubleValue}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句