In Swift 4 it's very straightforward with the Decodable
protocol:
let jsonString = """
[{"symbol":"ALI","date":"1/22/2018","open":44.9000,"high":45.5000,"low":44.9000,"close":45.2000,"bid":45.1500,"ask":45.2000,"volume":6698800,"value":303245610.0000,"netForeign":-42279365.0000}]
"""
struct Item : Decodable {
let symbol, date : String
let open, high, low, close, bid, ask, value, netForeign : Double
let volume : Int
}
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode([Item].self, from: data)
print(result)
} catch {
print("error: ", error)
}
Or even with decoding the date string as Date
struct Item : Decodable {
let symbol : String
let date : Date
let open, high, low, close, bid, ask, value, netForeign : Double
let volume : Int
}
do {
let data = Data(jsonString.utf8)
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let result = try decoder.decode([Item].self, from: data)
print(result)
} catch {
print("error: ", error)
}
This is an example to put JSONDecoder
and URLSession
together:
let url = URL(string: "https://api.whatever...")!
URLSession.shared.dataTask(with:url) { (data, _, error) in
if error != nil {
print(error!)
} else {
do {
let result = try JSONDecoder().decode([Item].self, from: data!)
print(result)
} catch {
print("error: ", error)
}
}
}.resume()
Please learn to read JSON. It's pretty simple. There are only two collection types (array, dictionary) and four value types (string, number, bool and null). See also my answer in this question: