I am trying to convert time series data received from the website alpha vantage to Swift object however the error message shown below prevents it from happening. Also my network function works. How do I resolve this ?
https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=IBM&apikey=demo
keyNotFound(CodingKeys(stringValue: "meta", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"meta\", intValue: nil) (\"meta\").", underlyingError: nil))
struct TimeSeriesMonthlyAdjusted :Decodable{
let meta: Meta
let timeSeries: [String:OHLC]
}
struct Meta :Decodable{
let symbol:String
enum CodingKey:String{
case symbol = "2. Symbol"
}
}
struct OHLC : Decodable{
let open :String
let close : String
let adjustedClose: String
enum CodingKey:String{
case open = "1. open"
case close = "4. close"
case adjustedClose = "5. adjusted close"
}
}
CodePudding user response:
So two things (which worked for me). Adding CodingKey
support TimeSeriesMonthlyAdjusted
struct TimeSeriesMonthlyAdjusted :Decodable{
enum CodingKeys:String, CodingKey {
case meta = "Meta Data"
case timeSeries = "Monthly Adjusted Time Series"
}
let meta: Meta
let timeSeries: [String:OHLC]
}
and changing enum CodingKey: String {...}
to enum CodingKeys: String, CodingKey {...}
for all your struct
s
Playground test
Make sure you add Test.json
to the Resources
folder in the Playground
struct TimeSeriesMonthlyAdjusted :Decodable{
enum CodingKeys:String, CodingKey {
case meta = "Meta Data"
case timeSeries = "Monthly Adjusted Time Series"
}
let meta: Meta
let timeSeries: [String:OHLC]
}
struct Meta :Decodable{
let symbol:String
enum CodingKeys:String, CodingKey{
case symbol = "2. Symbol"
}
}
struct OHLC : Decodable{
let open :String
let close : String
let adjustedClose: String
enum CodingKeys:String, CodingKey {
case open = "1. open"
case close = "4. close"
case adjustedClose = "5. adjusted close"
}
}
do {
let data = try Data(contentsOf: Bundle.main.url(forResource: "Test", withExtension: "json")!)
try JSONDecoder().decode(TimeSeriesMonthlyAdjusted.self, from: data)
} catch let error {
error
}
You might also want to make use of https://app.quicktype.io for quickly converting JSON to Swift