Quick and Easy JSON Swift 4.1

Yogesh Manghnani
codeburst
Published in
2 min readApr 7, 2018

--

It had always been a long and tedious task to parse JSON data in Swift. With Swift 4 it had become easy. And now with Swift 4.1 it has become even easier. The Decodable protocol is great.

Consider this JSON structure

[
{
id: 1;
name: "Yogesh"
image_url: "https://someurl.com/yogesh"
},
{
id: 2;
name: "Dan"
image_url: "https://someurl.com/dan"
},
{
id: 3;
name: "Zack"
image_url: "https://someurl.com/zack"
}
]

In Swift 4 with a struct agreeing to Decodable we can parse out thing in the manner as
Note:- data used below is the data that has already been fetched from the server.

//Swift 4.0
struct Person: Decodable {
let id: Int
let name: String
let image_url: String
}
let people = [Person]()func parseJSON(data: Data){
do {
let decoder = JSONDecoder()
self.people = try decoder.decode([Person].self, from: data)
} catch let error {
print(error as? Any)
}
}

The problem above is the image_url is in snake_case_name and we as Swift developers use camelCaseName and in Swift 4 we had to resolve this issue by doing stuff like below by using CodingKeys.
What CodingKeys enum lets you do is define custom keys for variables to parse out JSON.

//Swift 4.0
struct Person:Decodable {
let id: Int
let name: String
let imageUrl: String
//CodingKeys
private enum CodingKeys: String, CodingKey {
case imageUrl = "image_url"
case id, name
}
}

Above in Swift 4.0 we were able to parse out JSON with camelCase using CodingKeys. In Swift 4.1 it has become even more easier and quicker.

//Swift 4.1
struct Person: Decodable {
let id: Int
let name: String
let imageUrl: String
}
let people = [Person]()func parseJSON(data: Data){
do {
let decoder = JSONDecoder()
decoder.keyDecodingStratergy = .convertFromSnakeCase
self.people = try decoder.decode([Person].self, from: data)
} catch let error {
print(error as? Any)
}
}

The decoder.keyDecodingStratergy = .convertFromSnakeCase is what is new here and it’s great.

Follow me on GitHub, Instagram, Facebook, WordPress and Medium.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

I am fullstack developer who can’t sleep with bugs. (both in bed and in code)