JSON with snake case in Swift

Simplifying Data Manipulation with Snake Case in Swift

Balraj Verma
2 min readJun 13, 2023

When I was writing my previous blog post on Case Types in Programming, I considered including the same material there, but I decided that it would be best to keep this context entirely separate. And this would be a microblog 😊

Since there are many excellent blogs and tutorials available, we won’t go over full JSON parsing in Swift. We will just talk about what would happen if JSON supported various case types while delivering a response as opposed to a conventional one. Swift has one API for that to handle, let’s see below

//Json is using the snake case here to return the below output. 
//Sometime backend db use these naming convention, and its easier for back
//end developers to use the exact naming and response json(This is what i have seen sometime)
[
{
"company_name": "Test-Comp",
"company_location": "CA",
"no_of_employee": 200
}
]

As a result, there is one conventional strategy that developers may use if they are not aware of this API.

struct CompanyInfo: Codable {
var companyName: String
var companyLocation: String
var noOfEmployee: Int

private enum CodingKeys: String, CodingKey {
case companyName = "company_name"
case companyLocation = "company_location"
case noOfEmployee = "no_of_employee"
}
}

Although it will also function in the manner described above, it will be a little simpler to consume such JSON if we are familiar with Swift’s API below.

struct CompanyInfo: Codable {
var companyName: String
var companyLocation: String
var noOfEmployee: Int
}

//Here is the property we should use
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
/* You don't need to define your custom coding key
for converting JSON to a foundation object*/

This is it. If you notice a snake case being returned by JSON, I hope this may be of use.

If you like reading this blog, give it a thumbs up. I will see you in the next one 😊!!!

--

--

Balraj Verma
Balraj Verma

Written by Balraj Verma

Share What I Lean 😊 | Mobile Developer

No responses yet