ios - Swift 解码具有多种不同格式的数据类型

标签 ios codable decodable swift4.2

我从服务器返回了“几种”不同格式的 bool 值(对于相同的结构和字段)。我知道这很荒谬,但我需要找到一种方法来干净地处理它。

所以为了反序列化它,我做了类似的事情(示例程序):

import Foundation

struct Foo: Codable {
    var isOpen: Bool?

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        isOpen = try container.decodeIfPresent(Bool.self, forKey: .isOpen)
    }

    enum CodingKeys: String, CodingKey {
        case isOpen
    }
}

//He sends any one of these..
let json1 = "{ \"isOpen\": \"true\" }"
let json2 = "{ \"isOpen\": \"false\" }"
let json3 = "{ \"isOpen\": true }"
let json4 = "{ \"isOpen\": false }"
let json5 = "{ \"isOpen\": null }"
let json6 = "{ \"isOpen\": \"null\" }"
let json7 = "{ \"isOpen\": \"<null>\" }"

//He doesn't send this one.. but I wouldn't be surprised if I got it so I added it for fun (serializing the below `json8` and `json9` is not required for an answer).. :)

let json8 = "{ \"isOpen\": 0 }"
let json9 = "{ \"isOpen\": 1 }"

let json = [json1, json2, json3, json4, json5, json6, json7, json8, json9]
for js in json {
    if let rawData = js.data(using: .utf8) {
        do {
            let foo = try JSONDecoder().decode(Foo.self, from: rawData)
            if let isOpen = foo.isOpen {
                print("\(isOpen)\n\n")
            } else {
                print("State Unknown\n\n")
            }
        } catch {
            print("\(error)\n\n")
        }
    }
}

现在,如果我使用 Swift Codable(我们所有的数据结构都已使用它),那么我们将得到类型不匹配并抛出错误/异常。我考虑过 try catch 每个案例并尝试使用不同类型的另一个解码但最终会像这样:

do {
    isOpen = try container.decode(Bool.self, forKey: .isOpen)
}
catch {
    do {
        isOpen = try container.decode(Int.self, forKey: .isOpen) != 0
    }
    catch {
        do {
            isOpen = Bool(try container.decode(String.self, forKey: .isOpen))
        }
        catch {
            do {
                isOpen = try container.decodeIfPreset(Bool.self, forKey: .isOpen)  ?? GiveUpAndAssignDefaultValueHere..
            }
            catch {
                isOpen = nil //no idea..
            }
        }
    }
}

然后这让我开始考虑先将它转换为字符串,然后尝试解析它,所以我最终得到了(至少比上面的更好):

do {
    isOpen = try container.decode(Bool?.self, forKey: .isOpen)
}
catch {
    do {
        isOpen = Bool(try container.decode(String.self, forKey: .isOpen))
    }
    catch {
        isOpen = try container.decode(Int.self, forKey: .isOpen) != 0
    }
}

但肯定有更好的方法吗?有什么想法吗???

最佳答案

与其捕获错误,不如有条件地绑定(bind)类型

struct Foo: Codable {
    var isOpen: Bool?

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let boolOpen = try? container.decode(Bool.self, forKey: .isOpen) {
            isOpen = boolOpen
        } else if let intOpen = try? container.decode(Int.self, forKey: .isOpen) {
            isOpen = intOpen == 1
        } else if let stringOpen = try? container.decode(String.self, forKey: .isOpen) {
            switch stringOpen {
            case "true", "1": isOpen = true
            case "false", "0": isOpen = false
            default : isOpen = nil
            }
        } else {
            isOpen = nil
        }
    }
}

关于ios - Swift 解码具有多种不同格式的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52489023/

相关文章:

ios - 无需在 Swift 中创建附加类即可解码嵌套数据

ios - 如何使用 Swift Codable 将复杂的 Json 打印到 CollectionView?

Swift 4 解码简单的根级 json 值

swift - Alamofire 的通用功能

IOS:如何在 Swift 中增加 AVAudioPlayer 的低音和高音?

ios - 如何在 CollectionView 中使用延迟加载?

ios - Alamofire 响应与请求不匹配

ios - 在 UICollectionView 中创建缓慢滚动到 indexPath

ios - 如何使用 Swift Codable 处理部分动态的 JSON?

ios - 如何使 UIFont 符合 decodable