Swift:有一种方法可以快速调试可解码对象

时间:2020-01-22 07:55:11

标签: json swift codable

我有一个来自20个字段的对象。当我从服务器获取json时,会收到有关json解码的错误。

有一种方法可以快速找出哪个字段有问题,而不是删除所有字段并逐个放回去找出哪个字段有问题。

3 个答案:

答案 0 :(得分:5)

如果您使用 __str__ 来解析 JSON ,则只需在Codable块中打印error,然后它将打印出问题所在的完整详细信息。

catch

答案 1 :(得分:2)

只需在error块中打印error.localizedDescription实例(从不 catch)。

错误显示CodingPath和发生错误的受影响键。

答案 2 :(得分:0)

您还可以添加其他捕获块以准确了解错误的本质。

do {
    let decoder = JSONDecoder()
    let messages = try decoder.decode(Response.self, from: data)
    print(messages as Any)
} catch DecodingError.dataCorrupted(let context) {
    print(context)
} catch DecodingError.keyNotFound(let key, let context) {
    print("Key '\(key)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
    print("Value '\(value)' not found:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context) {
    print("Type '\(type)' mismatch:", context.debugDescription)
    print("codingPath:", context.codingPath)
} catch {
    print("error: ", error)
}