Skip to content

Instantly share code, notes, and snippets.

@nolochemical
Created March 12, 2020 16:27
Show Gist options
  • Save nolochemical/1df92f9ed21fa10a10bbd5f344016c97 to your computer and use it in GitHub Desktop.
Save nolochemical/1df92f9ed21fa10a10bbd5f344016c97 to your computer and use it in GitHub Desktop.
Fairly straight forward JSONDecoder with a single nest
import Foundation
let i = """
{
"Global Quote":{
"01. symbol": "MSFT",
"02. open": "157.1304",
"03. high": "157.7000",
"04. low": "151.1500",
"05. price": "153.6300",
"06. volume": "56029209",
"07. latest trading day": "2020-03-11",
"08. previous close": "160.9200",
"09. change": "-7.2900",
"10. change percent": "-4.5302%"
}
}
""".data(using: .utf8)
struct Quote: Decodable{
var symbol: String
var open: String
var high: String
var low: String
var price: String
var volume: String
var latestTrade: String
var previousClose: String
var change: String
var changePercent: String
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DecodingKeys.self)
symbol = try container.decode(String.self, forKey: .symbol)
open = try container.decode(String.self, forKey: .open)
high = try container.decode(String.self, forKey: .high)
low = try container.decode(String.self, forKey: .low)
price = try container.decode(String.self, forKey: .price)
volume = try container.decode(String.self, forKey: .volume)
latestTrade = try container.decode(String.self, forKey: .latestTrade)
previousClose = try container.decode(String.self, forKey: .previousClose)
change = try container.decode(String.self, forKey: .change)
changePercent = try container.decode(String.self, forKey: .changePercent)
}
}
struct Root: Decodable {
var quote: Quote
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DecodingKeys.self)
quote = try container.decode(Quote.self, forKey: .quote)
}
}
enum DecodingKeys: String, CodingKey {
case quote = "Global Quote"
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 latestTrade = "07. latest trading day"
case previousClose = "08. previous close"
case change = "09. change"
case changePercent = "10. change percent"
}
let decoder = JSONDecoder()
do {
let info = try decoder.decode(Root.self, from: i!)
print(info.quote.symbol)
} catch let e{
print(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment