【问题标题】:Decodable value String or Bool可解码值 String 或 Bool
【发布时间】:2019-03-21 01:04:53
【问题描述】:

我目前正在使用设计不佳的 JSON Api... 这总是返回一个值(例如,String、Int、Double...)或 false(非 null)。

使用 decodedable 处理此问题的最佳方法是什么,因为 Codable 不支持 Any?

密钥可能如下所示:

{
    "key": "Test",
}

或者像这样(我知道,应该是 null 而不是 false):

{
    "key": false,
}

这是不可能的:

struct Object: Decodable {
    let key: Any?
}

【问题讨论】:

  • 你的问题是什么?你的 API 是返回 unpredictable 类型还是什么?
  • 不是我的 API...但是当值为空时它返回 false 而不是 null...
  • 我认为你可以尝试将你的 let 键设置为可解码?然后你必须将你的密钥转换为你的类型

标签: ios swift codable


【解决方案1】:

我有同样的情况,ID 可以是 Int 或 String

class MyClass: Codable {
    let id: Int?
    required init(from decoder: Decoder) throws {
       let values = try decoder.container(keyedBy: CodingKeys.self)

       do {
           let stringId = try values.decodeIfPresent(String.self, forKey: .id)
            id = Int(stringId ?? "0")

          } catch {
             id = try values.decodeIfPresent(Int.self, forKey: .id)

         }
    }

  }

required init(from decoder: Decoder) throws 内部,我有另一个 do try 块,我在其中转换它

【讨论】:

    【解决方案2】:

    您可以创建一个通用包装器类型,如果键的值为false,则将nil 分配给Optional 值,否则它会解码该值。然后,您可以将它们包装在这个包装器中,而不是存储实际类型。

    struct ValueOrFalse<T:Decodable>: Decodable {
        let value:T?
    
        public init(from decoder:Decoder) throws {
            let container = try decoder.singleValueContainer()
            let falseValue = try? container.decode(Bool.self)
            if falseValue == nil {
                value = try container.decode(T.self)
            } else {
                value = nil
            }
        }
    }
    
    struct RandomJSONStruct: Decodable {
        let anInt:ValueOrFalse<Int>
        let aString:ValueOrFalse<String>
    }
    
    let noValueJson = """
    {
        "anInt": false,
        "aString": "Test"
    }
    """
    
    do {
        print(try JSONDecoder().decode(RandomJSONStruct.self, from: noValueJson.data(using: .utf8)!))
    } catch {
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2022-12-18
      相关资源
      最近更新 更多