How do you design a codable JSON field which can be either an empty string or an int [closed]

怎甘沉沦 提交于 2019-12-06 11:27:54

问题


How do you handle a field of a codable struct from JSON which can be either an empty string or an int? I tried using the data type any but that does not conform to codable. I think that if it does not have a value then it returns an empty string or otherwise, it returns an int. I am using Swift 4 and XCode 9. Thanks in advance


回答1:


I really would suggest changing that web service to return values consistently (and if there is no value for the integer type, don't return anything for that key).

But if you're stuck with this design, you will have to write your own init(from:) which gracefully handles the failure to parse the integer value. E.g.:

struct Person: Codable {
    let name: String
    let age: Int?

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        do {
            age = try values.decode(Int.self, forKey: .age)
        } catch {
            age = nil
        }
    }

}

I'd also advise against using 0 as a sentinel value for "no integer value provided". This is what optionals are for.



来源:https://stackoverflow.com/questions/46392046/how-do-you-design-a-codable-json-field-which-can-be-either-an-empty-string-or-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!