Created
October 4, 2018 08:15
-
-
Save shaktiprakash099/7fcb1222a1504ac57c22b8552afad6b2 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 Foundation | |
import UIKit | |
let json = """ | |
[{ | |
"first_name": "Shakti", | |
"last_name": "prakash", | |
"age":25, | |
"address":"Cuttack,Odisha,India" | |
}, | |
{ | |
"first_name": "Soumen", | |
"last_name": "Mohanty", | |
"age":25, | |
"address":null | |
}] | |
""" | |
let jsonData = Data(json.utf8) | |
struct Person: Codable{ | |
var firstName: String | |
var lastName: String | |
var age: Int | |
var address: String | |
private enum CodingKeys: String, CodingKey{ | |
case firstName = "first_name" | |
case lastName = "last_name" | |
case age | |
case address | |
} | |
init(from decoder: Decoder) throws{ | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
firstName = try container.decode(String.self, forKey: .firstName) | |
lastName = try container.decode(String.self, forKey: .lastName) | |
age = try container.decode(Int.self, forKey: .age) | |
address = (try container.decodeIfPresent(String.self, forKey: .address)) ?? "Unknown Address" | |
} | |
} | |
let decoder = JSONDecoder() | |
do { | |
let response = try decoder.decode([Person].self, from: jsonData) | |
print(response) | |
} catch let error { | |
print("Parsing Failed \(error.localizedDescription)") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment