Last active
August 18, 2021 08:58
-
-
Save vineethvijayan/883beb14a2f96bf61f8414af62437ca4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
//var str = "Hello, playground" | |
let json = """ | |
{ | |
"sample_data": [ | |
{ | |
"first_name": "vivek", | |
"age_number": "28", | |
"emp_id": 123 | |
}, | |
{ | |
"first_name": "deepak", | |
"age_number": "29", | |
"emp_id": "123" | |
}, | |
{ | |
"first_name": "renjith", | |
"age_number": "29", | |
"emp_id": "123" | |
}, | |
{ | |
"first_name": "akshay", | |
"emp_id": "123" | |
} | |
] | |
} | |
""" | |
struct Sample: Codable { | |
struct sampleData: Codable { | |
var firstName: String | |
var ageNumber: String | |
var empId: String | |
private enum CodingKeys: String, CodingKey { | |
case firstName = "first_name" | |
case ageNumber = "age_number" | |
case empId = "emp_id" | |
} | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
firstName = try values.decode(String.self, forKey: .firstName) | |
if let tmpAge = try? values.decode(String.self, forKey: .ageNumber) { | |
ageNumber = tmpAge | |
} | |
else { | |
ageNumber = "" | |
} | |
if let tmpEmpId = try? values.decode(String.self, forKey: .empId) { | |
empId = tmpEmpId | |
} | |
else { | |
empId = try String(values.decode(Int.self, forKey: .empId)) | |
} | |
} | |
} | |
var sample_data: [sampleData]? | |
} | |
let data = json.data(using: .utf8) | |
let obj = try! JSONDecoder().decode(Sample.self, from: data!) | |
print(obj.sample_data!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment