I have a JSON (from a third party) that I need to parse. This JSON returns several nested objects
articles: {
authors: {
birthday: 'DD-MM-YYYY'
}
relevant_until: 'YYYY-MM-DD HH:MM:SS'
publication_date: secondsSince1970,
last_comment: iso8601
}
I'm following this answer to have multiple date formatters and it works, as long as every date extracted from JSON is a string.
But when it comes to the secondsSince1970 (UNIX epoc time) I can't find a way to parse it as a codable object. Everywhere I see the Date(timeIntervalSince1970: timestamp) and I don't know how to use it when decoding it
How do I parse the dates on this object when a date can be passed as a TimeInterval or as a String?
try jsonDecoder.decode(Articles.self, from: jsonData)
extension Formatter {
static let iso8601withFractionalSeconds: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
static let ddMMyyyy: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd-MM-yyyy"
return formatter
}()
}
extension JSONDecoder.DateDecodingStrategy {
static let multiple = custom {
let container = try $0.singleValueContainer()
do {
return try Date(timeIntervalSince1970: container.decode(Double.self))
} catch DecodingError.typeMismatch {
let string = try container.decode(String.self)
if let date = Formatter.iso8601withFractionalSeconds.date(from: string) ??
Formatter.iso8601.date(from: string) ??
Formatter.ddMMyyyy.date(from: string) {
return date
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
}
}
}
Playground testing:
struct Root: Codable {
let articles: Articles
}
struct Articles: Codable {
let authors: Authors
let relevantUntil: Date
let publicationDate: Date
let lastComment: Date
}
struct Authors: Codable {
let birthday: Date
}
let json = """
{"articles": {
"authors": {"birthday": "01-01-1970"},
"relevant_until": "2020-11-19 01:23:45",
"publication_date": 1605705003.0019,
"last_comment": "2020-11-19 01:23:45.678"}
}
"""
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .multiple
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let root = try decoder.decode(Root.self, from: .init(json.utf8))
print(root.articles) // Articles(authors: __lldb_expr_107.Authors(birthday: 1970-01-01 03:00:00 +0000), relevantUntil: 2020-11-19 04:23:45 +0000, publicationDate: 2020-11-18 13:10:03 +0000, lastComment: 2020-11-19 04:23:45 +0000)
} catch {
print(error)
}
Following the same logic you can try to decode the JSON property as TimeInterval (or Double) and if that fails, fall back to your String handling:
extension JSONDecoder {
var dateDecodingStrategyFormatters: [DateFormatter]? {
#available(*, unavailable, message: "This variable is meant to be set only")
get { return nil }
set {
guard let formatters = newValue else { return }
self.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
do {
let timeInterval = try container.decode(TimeInterval.self)
return Date(timeIntervalSince1970: timeInterval)
} catch DecodingError.typeMismatch {
let dateString = try container.decode(String.self)
for formatter in formatters {
if let date = formatter.date(from: dateString) {
return date
}
}
}
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date")
}
}
}
}
Related
Was only able to reproduce this issue on a friend's device. The device is from Germany and is set to the German region in Settings. I cannot reproduce on any Canadian devices. Why is it failing when trying to create a Date property from the JSON?
Console:
dataCorrupted(Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "60", intValue: nil), CodingKeys(stringValue: "expiration", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil))
Struct:
struct TokenResponse: Decodable {
var ticket : String
var expiration : Date?
var sessionId: String
}
Inside URLSession:
do {
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(formatter)
let json = try decoder.decode([String: TokenResponse].self, from: data)
}
catch {
print(error)
}
JSON:
{
"60":{
"ticket":"aVeryLongJWT",
"expiration":"2022-02-04T22:00:34.8325102Z",
"sessionId":"aUUID"
}
}
You should set the locale before setting dateFormat string:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
See “Working With Fixed Format Date Representations” in DateFormatter documentation.
Previous answer is worked for me! You should check the date format coming from server. Mine was different and its case sensitive. I just arranged df.dateFormat Good luck!
private let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-hh:ss"
return df
}()
and then in the dataFetch function
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(self.dateFormatter)
let results = try! decoder.decode(Model.self, from: data)
print(results)
} catch {
print("Decoding Error!")
}
I have api file that returns the following JSONObject
{"result":[{"eventID":"1","regionID":"2","venue":"Saxafi Hotel","eventName":"VDATE","startDateTime":"2019-04-17 16:00:00","endDateTime":"2019-04-18 21:30:00"}]}
I can parse if its JSONArray
[{"eventID":"1","regionID":"2","venue":"Saxafi Hotel","eventName":"VDATE","startDateTime":"2019-04-17 16:00:00","endDateTime":"2019-04-18 21:30:00"}]
func parseJSON(_ data: Data){
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
}catch let error as NSError{
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let stock = StockModel()
if let name = jsonElement["venue"] as? String,
let price = jsonElement["regionID"] as? String
{
print(name)
print(price)
stock.name = name
stock.price = price
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: {() -> Void in
self.delegate.itemsDownload(items: stocks)
})
}
I am new in IOS I am familiar in Android and I was using to parse
this
JSONObject object = new JSONObject(response); JSONArray array=object.getJSONArray("result");
Your data types will look like,
// MARK: - Response
struct Response: Codable {
let result: [Result]
}
// MARK: - Result
struct Result: Codable {
let eventID, regionID, venue, eventName: String
let startDateTime, endDateTime: String
}
// Get Data from the API and decode response as below,
do {
let response = try JSONDecoder().decode(Response.self, from: data)
response.result.forEach { result in
print(result.eventName)
}
} catch {
print(error)
}
You can try
struct Root:Codable {
let result:[Result]
}
struct Result:Codable {
let eventID,regionID,venue,eventName:String
let startDateTime,endDateTime:Date
}
do {
let dec = JSONDecoder()
let df = DateFormatter()
df.dateFormat = "yyy-MM-dd HH:mm:ss"
dec.dateDecodingStrategy = .formatted(df)
let res = try dec.decode(Root.self, from:data)
}
catch {
print(error)
}
Or you can get rid of Root and do
do {
let con = try JSONSerialization.jsonObject(with:data) as! [String:Any]
let www = try JSONSerialization.data(withJSONObject:con["result"]!)
let dec = JSONDecoder()
let df = DateFormatter()
df.dateFormat = "yyy-MM-dd HH:mm:ss"
dec.dateDecodingStrategy = .formatted(df)
let res = try dec.decode([Result].self, from:www)
print(res)
}
catch {
print(error)
}
I deal with lots of objects that I serialize/deserialize to JSON using the Codable protocol.
It isn't that hard to create a JSONEncoder, set it up to pretty-print, convert the object to JSON, and then convert that to a string, but seems like a lot of work. Is there a simple way to say "please show me the JSON output for this object?"
EDIT:
Say for example I have the following structures:
struct Foo: Codable {
let string1: String?
let string2: String?
let date: Date
let val: Int
let aBar: Bar
}
struct Bar: Codable {
let name: String
}
And say I've created a Foo object:
let aBar = Bar(name: "Fred")
let aFoo = Foo(string1: "string1", string2: "string2", date: Date(), val: 42, aBar: aBar)
I could print that with a half-dozen lines of custom code:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(aFoo),
let output = String(data: data, encoding: .utf8)
else { fatalError( "Error converting \(aFoo) to JSON string") }
print("JSON string = \(output)")
Which would give the output:
JSON string = {
"date" : 557547327.56354201,
"aBar" : {
"name" : "Fred"
},
"string1" : "string1",
"val" : 42,
"string2" : "string2"
}
I get tired of writing the same half-dozen lines of code each time I need it. Is there an easier way?
I would recommend creating a static encoder so you don't create a new encoder every time you call that property:
extension JSONEncoder {
static let shared = JSONEncoder()
static let iso8601 = JSONEncoder(dateEncodingStrategy: .iso8601)
static let iso8601PrettyPrinted = JSONEncoder(dateEncodingStrategy: .iso8601, outputFormatting: .prettyPrinted)
}
extension JSONEncoder {
convenience init(dateEncodingStrategy: DateEncodingStrategy,
outputFormatting: OutputFormatting = [],
keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys) {
self.init()
self.dateEncodingStrategy = dateEncodingStrategy
self.outputFormatting = outputFormatting
self.keyEncodingStrategy = keyEncodingStrategy
}
}
Considering that you are calling this method inside a Encodable extension you can just force try!. You can also force the conversion from data to string:
extension Encodable {
func data(using encoder: JSONEncoder = .iso8601) throws -> Data {
try encoder.encode(self)
}
func dataPrettyPrinted() throws -> Data {
try JSONEncoder.iso8601PrettyPrinted.encode(self)
}
// edit if you need the data using a custom date formatter
func dataDateFormatted(with dateFormatter: DateFormatter) throws -> Data {
JSONEncoder.shared.dateEncodingStrategy = .formatted(dateFormatter)
return try JSONEncoder.shared.encode(self)
}
func json() throws -> String {
String(data: try data(), encoding: .utf8) ?? ""
}
func jsonPrettyPrinted() throws -> String {
String(data: try dataPrettyPrinted(), encoding: .utf8) ?? ""
}
func jsonDateFormatted(with dateFormatter: DateFormatter) throws -> String {
return String(data: try dataDateFormatted(with: dateFormatter), encoding: .utf8) ?? ""
}
}
Playground testing
struct Foo: Codable {
let string1: String
let string2: String
let date: Date
let val: Int
let bar: Bar
}
struct Bar: Codable {
let name: String
}
let bar = Bar(name: "Fred")
let foo = Foo(string1: "string1", string2: "string2", date: Date(), val: 42, bar: bar)
try! print("JSON\n=================\n", foo.json(), terminator: "\n\n")
try! print("JSONPrettyPrinted\n=================\n", foo.jsonPrettyPrinted(), terminator: "\n\n")
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
try! print("JSONDateFormatted\n=================\n", foo.jsonDateFormatted(with: dateFormatter))
This will print
JSON
=================
{"date":"2020-11-06T20:22:55Z","bar":{"name":"Fred"},"string1":"string1","val":42,"string2":"string2"}
JSONPrettyPrinted
=================
{
"date" : "2020-11-06T20:22:55Z",
"bar" : {
"name" : "Fred"
},
"string1" : "string1",
"val" : 42,
"string2" : "string2"
}
JSONDateFormatted
=================
{"date":"6 November 2020","bar":{"name":"Fred"},"string1":"string1","val":42,"string2":"string2"}
There isn't a stock way to convert a Codable object graph to a "pretty" JSON string, but it's pretty easy to define a protocol to do it so you don't write the same conversion code over and over.
You can simply create an extension to the Encodable protocol, like this:
extension Encodable {
var prettyJSON: String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self),
let output = String(data: data, encoding: .utf8)
else { return "Error converting \(self) to JSON string" }
return output
}
}
Then for any JSON object
print(myJSONobject.prettyJSON)
and it displays the JSON text in "pretty printed" form.
One thing the above won't do is support custom formatting of dates. To do that we can modify prettyJSON to be a function rather than a computed property, where it takes an optional DateFormatter as a parameter with a default value of nil.
extension Encodable {
func prettyJSON(formatter: DateFormatter? = nil) -> String {
let encoder = JSONEncoder()
if let formatter = formatter {
encoder.dateEncodingStrategy = .formatted(formatter)
}
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self),
let output = String(data: data, encoding: .utf8)
else { return "Error converting \(self) to JSON string" }
return output
}
}
Then you can use it just like the above, except that you need to add parentheses after prettyJSON, e.g.
print(myJSONobject.prettyJSON())
That form ignores the new DateFormatter parameter, and will output the same JSON string as the above. However,If you have a custom date formatter:
var formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy HH:mm:ss"
print(myJSONobject.prettyJSON(formatter: formatter))
Then the dates in your object graph will be formatted using the specified DateFormatter
I've been trying to work with the below code to get my JSON data. It returns "Error after loading". I am using this JSON data in another application and it works. I'm trying to implement the new simplified method using Swift 4. The code does work to the point of the print statement "downloaded".
class MortgageRatesVC: UIViewController {
final let url = URL (string:"http://mortgous.com/JSON/currentRatesJSON.php")
override func viewDidLoad() {
super.viewDidLoad()
downloadJason()
}
func downloadJason () {
guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("Oops Call for Help")
return
}
print("downloaded")
do
{
let decoder = JSONDecoder()
let rates = try decoder.decode([LenederRates].self, from: data)
print(rates)
} catch {
print("Error after loading")
}
}.resume()
}
}
Class
class LenederRates: Codable {
let key : String
let financial_institution : String
let variable_rate : String
let six_months : String
let one_year : String
let two_year : String
let three_year : String
let four_year : String
let five_year : String
// let date : Date
init(key: String, financial_institution: String, variable_rate: String, six_months: String, one_year: String, two_year: String, three_year: String, four_year: String, five_year: String) {
self.key = key
self.financial_institution = financial_institution
self.variable_rate = variable_rate
self.six_months = six_months
self.one_year = one_year
self.two_year = two_year
self.three_year = three_year
self.four_year = four_year
self.five_year = five_year
}
}
The problem is the missing property date in your Codable class. You need to set the decoder dateDecodingStrategy to .formatted and pass a fixed format dateFormatter. Btw I suggest changing your class for a struct, change your property names using the Swift naming convention camelCase and provide the custom CodingKeys:
struct LenederRates: Codable {
let key: String
let financialInstitution : String
let variableRate: String
let sixMonths: String
let oneYear: String
let twoYear: String
let threeYear: String
let fourYear: String
let fiveYear: String
let date: Date
private enum CodingKeys: String, CodingKey {
case key, financialInstitution = "financial_institution", variableRate = "variable_rate", sixMonths = "six_months", oneYear = "one_year", twoYear = "two_year", threeYear = "three_year", fourYear = "four_year", fiveYear = "five_year", date
}
}
let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
guard let data = data else { return }
do {
let dateFormat = DateFormatter()
dateFormat.locale = Locale(identifier: "en_US_POSIX")
dateFormat.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormat)
let rates = try decoder.decode([LenederRates].self, from: data)
print(rates)
} catch {
print(error)
}
}.resume()
I am getting a response from an API but the problem is that the API is sending values back as a string of dates and doubles. I am therefore getting the error "Expected to decode Double but found a string/data instead." I have structured my struct like this to solve the problem but this seems like a patch. Is there any better way to fix this issue? I feel like apple has thought of this and included something natively to address this.
struct SimpleOrder:Codable{
var createdDate:Date! {
return createdDateString.dateFromISO8601
}
var createdDateString:String
var orderId:String!
var priceVal:Double!
var priceString:String{
didSet {
priceVal = Double(self.priceString)!
}
}
private enum CodingKeys: String, CodingKey {
//case createdDate
case createdDateString = "time"
case orderId = "id"
case priceVal
case priceString = "price"
}
}
I don't know if this is relevant but this is how it is being used. I am getting the data as a string and converting it to data which is stored in the dataFromString variable
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 //This is irrelevant though because the date is returned as a string.
do{
let beer = try decoder.decode(SimpleOrder.self, from: dataFromString)
print ("beer is \(beer)")
}catch let error{
print ("error is \(error)")
}
As a result of using codable, I am getting an error when trying to get an empty instance of SimpleOrder. Before I was using codable, I had no issues using SimpleOrder() without any arguments.
Error: Cannot invoke initializer for type 'SimpleOrder' with no arguments
var singlePoint = SimpleOrder()
struct SimpleOrder: Codable {
var created: Date?
var orderId: String?
var price: String?
private enum CodingKeys: String, CodingKey {
case created = "time", orderId = "id", price
}
init(created: Date? = nil, orderId: String? = nil, price: String? = nil) {
self.created = created
self.orderId = orderId
self.price = price
}
}
extension SimpleOrder {
var priceValue: Double? {
guard let price = price else { return nil }
return Double(price)
}
}
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
Decoding the json data returned by the API:
let jsonData = Data("""
{
"time": "2017-12-01T20:41:48.700Z",
"id": "0001",
"price": "9.99"
}
""".utf8)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Formatter.iso8601)
do {
let simpleOrder = try decoder.decode(SimpleOrder.self, from: jsonData)
print(simpleOrder)
} catch {
print(error)
}
Or initialising a new object with no values:
var order = SimpleOrder()