Forked from shaktiprakash099/codableProtocols.swift
Created
December 15, 2019 20:26
-
-
Save shanecowherd/0cfca49e055f78c090eaef450a717bf2 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
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) | |
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 | |
} | |
} | |
extension VariacType { | |
var Value:String { | |
switch self { | |
case .int(let intvalue): | |
return String(intvalue) | |
case .string(let stringValue): | |
return stringValue | |
} | |
} | |
} | |
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 | |
} | |
func encode(to Encoder: Encoder) throws{ | |
} | |
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.Value) | |
} 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