ignoe/bypass the key if value is nil after decoder in swift

37 Views Asked by At

My process is I have bunch of json string that I need to convert into request payload and make a POST request to api call. The issue is key may or may not exist from my original json string and the API does not accept nil as value. So the API call failed after decode if the key does not exist. The snippet code from mine is like following I transfer into decoable type. I search online and found the way decodeIfPresent in swift5 How can I do it?

struct Student: Codable {
    var name: String
    var skill: String?

    public enum Student: String, CodingKey {
        case name
        case skill
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Student.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.skill = try container.decodeIfPresent(String.self, forKey: .skill)
    }
}
let testString = "{\"name\": \"withSkill\", \"skill\": \"yell\"}"
let testStringB = "{\"name\": \"no Skill\"}"
let data = testString.data(using: .utf8)!
let dataB = testStringB.data(using: .utf8)!
let decodeData = try? JSONDecoder().decode(Student.self, from: data)
let decodeDataB = try? JSONDecoder().decode(Student.self, from: dataB)
/// what I get
▿ Optional<Student>
    ▿ some : Student
        - name : "no Skill"
        - skill : nil

/// what I want
▿ Optional<Student>
    ▿ some : Student
        - name : "no Skill"
0

There are 0 best solutions below