Skip to content

Instantly share code, notes, and snippets.

@mukyasa
Last active June 24, 2020 19:44
Show Gist options
  • Save mukyasa/48116c41f65fc9e555d3af64c5a7b8be to your computer and use it in GitHub Desktop.
Save mukyasa/48116c41f65fc9e555d3af64c5a7b8be to your computer and use it in GitHub Desktop.
let serviceOneJSON = """
{
"user_name": "Mukesh",
"user_tagline": "Experience is the name everyone gives to their mistakes",
"id": 1
}
""".data(using: .utf8)!
let serviceTwoJSON = """
{
"full_name": "Mukesh Mandora",
"status": "In order to be irreplaceable, one must always be different",
"user_id": 12
}
""".data(using: .utf8)!
struct UserOfProduct: Decodable {
var name: String?
var userId: Int?
var tagline: String?
enum ServiceOneCodingKeys: String, CodingKey {
case name = "user_name"
case userId = "id"
case tagline = "user_tagline"
}
enum ServiceTwoCodingKeys: String, CodingKey {
case name = "full_name"
case userId = "user_id"
case tagline = "status"
}
init(from decoder: Decoder) throws {
// Service One JSON Container
let containerForServiceOne = try decoder.container(keyedBy: ServiceOneCodingKeys.self)
userId = try containerForServiceOne.decodeIfPresent(Int.self,
forKey: .userId)
name = try containerForServiceOne.decodeIfPresent(String.self,
forKey: .name)
tagline = try containerForServiceOne.decodeIfPresent(String.self,
forKey: .tagline)
// Check any one param which is required to not be nil in this case
// userId, based on that we will take decision to decode from another container
guard userId == nil else {
return
}
// Service Two JSON Container
let containerForServiceTwo = try decoder.container(keyedBy: ServiceTwoCodingKeys.self)
userId = try containerForServiceTwo.decodeIfPresent(Int.self,
forKey: .userId)
name = try containerForServiceTwo.decodeIfPresent(String.self,
forKey: .name)
tagline = try containerForServiceTwo.decodeIfPresent(String.self,
forKey: .tagline)
// Failure send crash report to find this unknown keys
guard userId != nil else {
fatalError("Decooding error")
}
}
}
let userObjectFromServiceOne = try! JSONDecoder().decode(UserOfProduct.self, from: serviceOneJSON)
print("User Name from Service One, \(userObjectFromServiceOne.name ?? "")")
print("User Tagline from Service One, \(userObjectFromServiceOne.tagline ?? "")")
let userObjectFromServiceTwo = try! JSONDecoder().decode(UserOfProduct.self, from: serviceTwoJSON)
print("User Name from Service Two, \(userObjectFromServiceTwo.name ?? "")")
print("User Tagline from Service Two, \(userObjectFromServiceTwo.tagline ?? "")")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment