Created
October 4, 2018 11:07
-
-
Save shaktiprakash099/efa92f673181a59db325adce035573e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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) | |
enum VariacType:Codable{ | |
func encode(to encoder: Encoder) throws { | |
} | |
case int(Int) | |
case string(String) | |
init(from decoder: Decoder) throws { | |
if let intValue = try? decoder.singleValueContainer().decode(Int.self) { | |
self = .int(intValue) | |
return | |
} | |
if let stringValue = try? decoder.singleValueContainer().decode(String.self){ | |
self = .string(stringValue) | |
return | |
} | |
throw VariacError.missingValue | |
} | |
enum VariacError: Error { | |
case missingValue | |
} | |
} | |
struct Person: Codable{ | |
var firstName: String | |
var lastName: String | |
var age: VariacType | |
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(VariacType.self, forKey: .age) | |
age = (try container.decodeIfPresent(VariacType.self, forKey: .age)) ?? VariacType.int(0) | |
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[0].age) | |
} 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