This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathJSONDecoderExtension.swift
More file actions
52 lines (42 loc) · 1.57 KB
/
JSONDecoderExtension.swift
File metadata and controls
52 lines (42 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Foundation
extension JSONDecoder {
static var apiDecoder: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.supportMultipleDateFormats
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}
}
extension JSONDecoder.DateDecodingStrategy {
enum DateFormat: String, CaseIterable {
case noTime = "yyyy-mm-dd"
case dateWithTime = "yyyy-MM-dd HH:mm:ss"
case iso8601 = "yyyy-MM-dd'T'HH:mm:ssZ"
case iso8601WithMilliseconds = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
var formatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = rawValue
return dateFormatter
}
}
static var supportMultipleDateFormats: JSONDecoder.DateDecodingStrategy {
return JSONDecoder.DateDecodingStrategy.custom({ (decoder) -> Date in
let container = try decoder.singleValueContainer()
let dateStr = try container.decode(String.self)
var date: Date?
for format in DateFormat.allCases {
date = format.formatter.date(from: dateStr)
if date != nil {
break
}
}
guard let calculatedDate = date else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Cannot decode date string \(dateStr)"
)
}
return calculatedDate
})
}
}