如何设计可编码的JSON字段,该字段可以为空字符串或int [英] How do you design a codable JSON field which can be either an empty string or an int

查看:371
本文介绍了如何设计可编码的JSON字段,该字段可以为空字符串或int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处理来自JSON的可编码结构的字段,该字段可以为空字符串或int?我尝试使用任何数据类型,但不符合可编码的数据类型.我认为如果没有值,则返回空字符串,否则返回int.我正在使用Swift 4和XCode 9.

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

推荐答案

我真的建议更改该Web服务以一致地返回值(如果整数类型没有值,则不要为该键返回任何值)

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).

但是,如果您坚持使用此设计,则必须编写自己的init(from:),它可以优雅地处理解析整数值的失败.例如:

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
        }
    }

}

我也建议不要将0用作未提供整数值"的标记值.这是可选的.

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

这篇关于如何设计可编码的JSON字段,该字段可以为空字符串或int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆