gpt4 book ai didi

json - Alamofire 4.0 JSOn 解析 Swift

转载 作者:行者123 更新时间:2023-11-30 12:51:19 25 4
gpt4 key购买 nike

我是 Alamofire 的新手,我正在测试一些 API。我接触到了外汇汇率。所以JSON文件是这样的

["base": CAD, "date": 2016-12-01, "rates": {
AUD = "1.0097";
BGN = "1.3735";
BRL = "2.57";
CHF = "0.7559";
CNY = "5.1388";
CZK = "19.004";
DKK = "5.2248";
EUR = "0.70225";
GBP = "0.59058";
HKD = "5.7881";
HRK = "5.2985";
HUF = "220.48";
IDR = 10108;
ILS = "2.8607";
INR = "51.009";
JPY = "85.246";
KRW = "871.9400000000001";
MXN = "15.403";
MYR = "3.331";
NOK = "6.2941";
NZD = "1.0539";
PHP = "37.102";
PLN = "3.1374";
RON = "3.1631";
RUB = "47.591";
SEK = "6.8775";
SGD = "1.0657";
THB = "26.616";
TRY = "2.6006";
USD = "0.7462800000000001";
ZAR = "10.504";}]

typealias JSONStandard = [String: AnyObject]

func parseData(JSONData:Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
if let rates = readableJSON["rates"] as? JSONStandard{
for i in 0..<rates.count {
let rate = rates[i] as! //Here
}
print(rates)
}
print(readableJSON)

} catch {
print(error)
}
}

我能够获得侧面“费率”,但我不知道如何解析“费率”内的所有数据。我想我必须把它保存在字典中。很困惑谢谢

最佳答案

正如您所看到的,它是 String 中的 double 值,因此您需要先将 AnyObject 转换为 String,然后再将其转换为 Double。你可以这样做(在 Swift Playground 中测试):

import Foundation

typealias JSONStandard = [String: AnyObject]

func parseData(JSONData:Data) {
do {
guard let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as? JSONStandard,
let ratesJSON = readableJSON["rates"] as? JSONStandard
else { return }
print("Readable JSON :")
print(readableJSON)
let rates = ratesJSON.flatMap({ (key, value) -> ([String: Double]) in
guard let value = value as? String, let convertedValue = Double(value) else { return [:] }
return [key: convertedValue]
})
print("Rates :")
print(rates)

} catch {
print(error)
}
}

let jsonString = "{\"base\": \"CAD\", \"date\": \"2016-12-01\", \"rates\": { \"AUD\": \"1.0097\", \"BGN\": \"1.3735\", \"BRL\": \"2.57\"}}"
let jsonData = jsonString.data(using: String.Encoding.utf8)!
parseData(JSONData: jsonData)

结果:

Readable JSON :
["base": CAD, "date": 2016-12-01, "rates": {
AUD = "1.0097";
BGN = "1.3735";
BRL = "2.57";
}]
Rates :
[("BGN", 1.3734999999999999), ("AUD", 1.0097), ("BRL", 2.5699999999999998)]

关于json - Alamofire 4.0 JSOn 解析 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40922664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com