我正在重构一些我以前使用第三方 JSON 解析器的项目,我遇到了一个愚蠢的网站,它返回一个布尔值作为字符串。
这是来自 JSON 响应的相关片段:
{
"delay": "false",
/* a bunch of other keys*/
}
我的解码结构如下所示:
struct MyJSONStruct: Decodable {
let delay: Bool
// the rest of the keys
}
我如何将 JSON 响应中返回的字符串转换为 Bool 以匹配我在 Swift 4 中的结构?虽然这篇文章很有帮助,但我不知道如何将字符串响应转换为布尔值。
基本上你必须编写一个自定义初始化程序,但是如果有很多好的键但只有一个可以从一种类型映射到另一种类型,那么计算属性可能很有用
struct MyJSONStruct: Decodable {
var delay: String
// the rest of the keys
var boolDelay : Bool {
get { return delay == "true" }
set { delay = newValue ? "true" : "false" }
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句