使用 Swift 4 Decodable 将字符串 JSON 响应转换为布尔值

Convert string JSON response to a boolean using Swift 4 Decodable

我正在重构一些我以前使用第三方 JSON 解析器的项目,我遇到了一个愚蠢的网站,returns 一个布尔值作为字符串。

这是 JSON 回复中的相关片段:

{
    "delay": "false",
    /* a bunch of other keys*/
}

我的解码结构如下所示:

struct MyJSONStruct: Decodable {
  let delay: Bool
  // the rest of the keys
}

如何将 JSON 响应中返回的字符串转换为 Bool 以匹配 Swift 4 中的结构?虽然 this post 很有帮助,但我不知道如何将字符串响应转换为布尔值。

基本上你必须编写一个自定义初始化器,但是如果有很多 good 键,但只有一个键可以从一种类型映射到另一种类型,那么计算 属性 可能会有用

struct MyJSONStruct: Decodable {
   var delay: String
   // the rest of the keys

   var boolDelay : Bool {
       get { return delay == "true" }
       set { delay = newValue ? "true" : "false" }
   }
}

您需要在 URLEncoding 初始值设定项中设置 boolEncoding: .literal。

boolEncoding: .literal