How to use JSON Codable in Swift 4

Issue #63

Codable in Swift 4 changes the game. It deprecates lots of existing JSON libraries.

Generic model

API responses is usually in form of an object container with a key. Then it will be either nested array or object. We can deal with it by introducing a data holder. Take a look DataHolder

1
2
3
4
5
6
7
8
9
10
{
"data": [
{
"comment_id": 1
},
{
"comment_id": 2
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct ListHolder<T: Codable>: Codable {
enum CodingKeys: String, CodingKey {
case list = "data"
}

let list: [T]
}

struct OneHolder<T: Codable>: Codable {
enum CodingKeys: String, CodingKey {
case one = "data"
}

let one: T
}

then with Alamofire, we can just parse to data holder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func loadComments(mediaId: String, completion: @escaping ([Comment]) -> Void) {
request("https://api.instagram.com/v1/media/\(mediaId)/comments",
parameters: parameters)
.responseData(completionHandler: { (response) in
if let data = response.result.value {
do {
let holder = try JSONDecoder().decode(ListHolder<Comment>.self, from: data)
DispatchQueue.main.async {
completion(holder.list)
}
} catch {
print(error)
}
}
})
}

Read more

Comments