Swift:有办法快速调试可解码对象

Mic*_*sen 4 json swift codable

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

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

PGD*_*Dev 10

如果您正在使用Codable解析JSON,您可以简单地打印errorincatch块,它将打印出问题所在位置的完整详细信息。

do {
    let response = try JSONDecoder().decode(Root.self, from: data)
    print(response)
} catch {
    print(error) //here.....
}
Run Code Online (Sandbox Code Playgroud)


小智 7

您还可以添加额外的 catch 块以准确了解错误的性质。

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)
}
Run Code Online (Sandbox Code Playgroud)


vad*_*ian 5

只需在块中打印error实例(从不 error.localizedDescriptioncatch

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