Welcome to this tutorial of coding with appcodezip, we will learn about decodable.We often use JSON to send and receive data from web services.
Getting Started With Network Request, URLSession
[{ "empid": 1, "name": "Mr.Sushil Kumar", "role": "Developer", "org":"AppCodeZip", "depid":12755 }, { "empid": 2, "name": "Mr.Sunil Kumar", "role": "Developer", "org":"AppCodeZip", "depid":12756 }]
Let’s create a single view iOS Application in which we’ll parse the data through JSONDecoder.
Here I have a piece of code.I have an ViewController which is having a function called as getAppcodezipData and inside this function, you can see the code
func getAppcodezipData()
{
let url = "http://demo8044402.mockable.io/appcodezip"
URLSession.shared.dataTask(with: URL(string: url)!) { (responseData, httpUrlResponse, error) in
if(error == nil && responseData != nil && responseData?.count != 0)
{
//parse the responseData here
}
}.resume()
}
struct EmployeeResponse : Decodable
{
let empId, depid: Int
let name, role, org: String
}
JSON Parsing with JSONDecoder-
The rest of the JSON network request
import UIKit
struct EmployeResponse : Decodable
{
let empid, depid: Int
let name, role, org: String
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getAppcodezipData()
}
func getAppcodezipData()
{
let url = "http://demo8044402.mockable.io/appcodezip"
URLSession.shared.dataTask(with: URL(string: url)!) { (responseData, httpUrlResponse, error) in
if(error == nil && responseData != nil && responseData?.count != 0)
{
//parse the responseData here
let decoder = JSONDecoder()
do {
//for json with collection
let result = try decoder.decode([EmployeResponse].self, from: responseData!)
print(result)
for employee in result
{
print(employee.name)
}
}
catch let error
{
print("error occured while decoding = \(error.localizedDescription)")
}
}
}.resume()
}
}
I have used the model [EmployeResponse].self because we’re getting the response in an array format. If your response
Custom key names(Case sensitive and underscore key)-
We can modify our Codable key with custom string keys, but they should match your JSON response keys.
Swift uses the decodable protocol to internally map the JSON response to a struct or class that inherits from the decodable protocol, you can also use the coding keys enum to instruct swift if it needs to do some custom mapping.
There are scenarios where the API response may have underscore in their keys as- dep_id and emp_id.
{ "emp_id": 1, "Name": "Mr.Sushil Kumar", "role": "Developer", "org":"AppCodeZip", "dep_id":12755 }
You can update the variable name with an underscore but writing underscore is not good naming convention practice as per the variable declaration we should avoid writing underscore in variables.this is called custom mapping.
struct EmployeResponse : Decodable
{
let empid, depid: Int
let name, role, org: String
enum CodingKeys: String, CodingKey {
case depid = "dep_id"
case empId = "emp_id"
case name = "Name"
case role,org
}
}
For your complete source code, you can download the 👉 final project from GitHub. As always, leave us comment and share your thought about the tutorial.
I hope this article was helpful to you. So, please share it together with your friends and colleagues using the social buttons below!
0 Comments