我正在尝试解析这个json文件
{
"Global Quote": {
"01. symbol": "AAPL",
"02. open": "122.6000",
"03. high": "123.3500",
"04. low": "121.5400",
"05. price": "121.7800",
"06. volume": "79075988",
"07. latest trading day": "2020-12-14",
"08. previous close": "122.4100",
"09. change": "-0.6300",
"10. change percent": "-0.5147%"
} }
我想解析他的 JSON 文本,但不太确定为什么我的结构没有填充这个全局引用对象,而是将其留空。
struct GlobalQuote: Codable{
var symbol: String?
var open: String?
var high: String?
var low: String?
var price: String?
var volume: String?
var latestTradingDay: String?
var previousClose: String?
var change: String?
var changepercent: String?
private enum codingKeys : String, CodingKey {
case symbol = "01. symbol"
case open = "02. open"
case high = "03. high"
case low = "04. low"
case price = "05. price"
case volume = "06.volume"
case latestTradingDay = "07. latest trading day"
case previousClose = "08. previous close"
case change = "09. change"
case changepercent = "10. change percent"
}
}
...它在控制台中返回此..
GlobalQuote(symbol: nil, open: nil, high: nil, low: nil, price: nil, volume: nil, latestTradingDay: nil, previousClose: nil, change: nil, changepercent: nil)
...不太确定为什么我没有收到我的数据。
要解码 JSON,您首先需要将
codingKeys
结构体的 GlobalQuote
内部枚举更改为 CodingKeys
。 (大写开头)
然后您需要另一个结构来表示外部 JSON 对象,如下所示:
struct ResponseGlobalQuote: Codable {
var globalQuote: GlobalQuote
enum CodingKeys: String, CodingKey {
case globalQuote = "Global Quote"
}
}
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(ResponseGlobalQuote.self, from: data)
print(decoded)
} catch {
print(error)
}
或修改您的解码以使用
[String: GlobalQuote]
作为解码类型:
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode([String: GlobalQuote].self, from: Data(jsonString.utf8))
print(decoded.values.first)
} catch {
print(error)
}