Skip to content

Instantly share code, notes, and snippets.

@codecat15
Created December 19, 2022 15:10
Show Gist options
  • Save codecat15/11fe73dcf04de650aa3a30f60b4bd155 to your computer and use it in GitHub Desktop.
Save codecat15/11fe73dcf04de650aa3a30f60b4bd155 to your computer and use it in GitHub Desktop.
Custom Decoding when all JSON properties are received as string from API response
import Foundation
// MARK: Project model
struct Project: Decodable {
let id: Int
let name: String
let teamId: Int
let isActive: Bool
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case teamId = "teamId"
case isActive = "isActive"
}
// NOTE: Use optional properties whereever required
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Manually decoding the string response and storing them in variable
let id = try container.decode(String.self, forKey: .id)
let teamId = try container.decode(String.self, forKey: .teamId)
let isActive = try container.decode(String.self, forKey: .isActive)
self.id = Int(id) ?? 0 // converting the string response to int
self.name = try container.decode(String.self, forKey: .name)
self.teamId = Int(teamId) ?? 0 // converting the string response to int
self.isActive = Bool(isActive) ?? false // converting the string response to bool
}
}
// MARK: Employee model
struct Employee: Decodable {
let id: Int
let name: String
let projects: Array<Project>
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case projects = "projects"
}
// NOTE: Use optional properties whereever required
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Manually decoding the string response and storing them in variable
let id = try container.decode(String.self, forKey: .id)
self.id = Int(id) ?? 0 // converting the string response to int
self.name = try container.decode(String.self, forKey: .name)
self.projects = try container.decode([Project].self, forKey: .projects)
}
}
class Playground {
let jsonString = """
{
"id": "1",
"name": "Bruce",
"projects": [
{
"id": "123",
"name": "TodoList",
"teamId": "15",
"isActive": "true"
}
]
}
"""
func decodeJson() {
do {
let data = Data(jsonString.utf8)
let result = try JSONDecoder().decode(Employee.self, from: data)
print(result.id)
result.projects.forEach { project in
print(project.name)
print(project.teamId)
print(project.isActive)
}
}
catch {
print(error.localizedDescription)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment