How do you create a JSON encoded field that can be an empty string or int

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

+2
json swift field codable
source share
1 answer

I would suggest changing this web service to return values ​​sequentially (and if there is no value for the integer type, do not return anything for this key).

But if you're stuck with this design, you'll have to write your own init(from:) , which gracefully handles rejection of parsing an integer value. For example:.

 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 would also recommend using 0 as a reference value for "no integer value provided". This requires options.

+2
source share

All Articles