我在解码以下JSON(它完全包含在数组中(时遇到问题:
[
{
"symbol": "AAPL",
"name": "Apple Inc.",
"price": 254.81,
"changesPercentage": 2.85,
"change": 7.07,
"dayLow": 249.4,
"dayHigh": 255.5,
"yearHigh": 327.85,
"yearLow": 170.27,
"marketCap": 1114915995648,
"priceAvg50": 281.9003,
"priceAvg200": 270.52628,
"volume": 37900589,
"avgVolume": 48846970,
"exhange": "NASDAQ",
"open": 250.74,
"previousClose": 247.74,
"eps": 12.595,
"pe": 20.231043,
"earningsAnnouncement": "2020-01-28T21:30:00.000+0000",
"sharesOutstanding": 4375479808,
"timestamp": 1585600706
}
]
这是我用来解码的结构:
struct StockData: Codable {
let name: String
let exchange: String
let price: Double
let yearLow: Double
let yearHigh: Double
let marketCap: Double
}
这是我解码它的代码:
func parseJSON(_ stockData: Data) -> StockModel? {
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(StockData.self, from: stockData)
let name = decodedData.name
let exchange = decodedData.exchange
let price = String(decodedData.price)
let yearLow = String(decodedData.yearLow)
let yearHigh = String(decodedData.yearHigh)
let marketCap = String(decodedData.marketCap)
let stockModel = StockModel(name: name, exchange: exchange, stockAttributes: [price, marketCap, yearLow, yearHigh])
return stockModel
}catch{
print(error)
return nil
}
}
我试着把它做成:try decoder.decode([StockData].self, from: stockData)
,这样stockData就被括在括号里,表明它是一个数组,但我得到了错误
如何解码完全包含在数组中的JSON?
[StockData].self
是对的。错误(和JSON(清楚地表明根对象是一个数组。
要提取数据,请获取阵列的第一项
func parseJSON(_ stockData: Data) -> StockModel? {
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode([StockData].self, from: stockData)
guard let stock = decodedData.first else { return nil }
let name = stock.name
let exchange = stock.exchange
let price = String(stock.price)
let yearLow = String(stock.yearLow)
let yearHigh = String(stock.yearHigh)
let marketCap = String(stock.marketCap)
let stockModel = StockModel(name: name, exchange: exchange, stockAttributes: [price, marketCap, yearLow, yearHigh])
return stockModel
} catch {
print(error)
return nil
}
}
请阅读Swift语言指南