我目前正在尝试解析从IEX api返回的JSON。我遇到的问题是响应是动态的,取决于您请求的股票名称,JSON响应中的键会更改。因此,当请求AAPL股票信息时,返回的JSON是:
{"AAPL":{"quote":{"symbol":"AAPL","companyName":"Apple Inc.","primaryExchange":"Nasdaq Global Select","sector":"Technology","calculationPrice":"close","open":158.53,"openTime":1546266600303,"close":157.74,"closeTime":1546290000568,"high":159.36,"low":156.48,"latestPrice":157.74,"latestSource":"Close"}}
在一次请求中请求多只股票将返回JSON,可在此处查看:https://api.iextrading.com/1.0/stock/market/batch?symbols=AAPL,GOOGL,AAPL&types=quote,chart&range=1m
我正在使用的可解码结构如下:
struct Symbol: Decodable {
let quote: Quote
let chart: [Chart]
}
struct Chart: Decodable {
let date: String
let open, high, low, close: Double
let volume, unadjustedVolume: Int
let change, changePercent, vwap: Double
let label: String
let changeOverTime: Double
}
struct Quote: Decodable {
let symbol, companyName, primaryExchange, sector: String
let calculationPrice: String
let open: Double
let openTime: Int
let close: Double
let closeTime: Int
let high, low, latestPrice: Double
let latestSource, latestTime: String
let latestUpdate, latestVolume: Int
let delayedPrice: Double
let delayedPriceTime: Int
let extendedPrice, extendedChange, extendedChangePercent: Double
let extendedPriceTime: Int
let previousClose, change, changePercent: Double
let avgTotalVolume: Int
let marketCap: Int
let peRatio, week52High, week52Low, ytdChange: Double
}
使用
let parsedData = try JSONDecoder().decode([String:Symbol].self, from: data!)
有效,但是当尝试仅访问Symbol对象时,我仅获得nil值,所以我不知道发生了什么。我正在寻找像C#中的JSON.net这样的解决方案,使您能够做到
let parsedData = try JSONDecoder().decode(dictionary<String,Symbol>, from: data!)