Swift: 有快速调试可解码对象的方法
Swift: There is way to debug decodable object quickly
我有一个来自 20 个字段的对象。当我从服务器获取 json 时,我收到有关 json.
解码的错误
有一种方法可以快速找出哪个字段有问题,而不是删除所有字段然后一个接一个地放回去找出哪个字段有问题。
如果您使用 Codable
来解析您的 JSON,您只需打印 error
在 catch
块中,它将打印问题所在位置的完整详细信息。
do {
let response = try JSONDecoder().decode(Root.self, from: data)
print(response)
} catch {
print(error) //here.....
}
只需在 catch
块中打印 error
实例(never error.localizedDescription
)。
错误显示 CodingPath
和发生错误的受影响的键。
您还可以添加额外的 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)
}
我有一个来自 20 个字段的对象。当我从服务器获取 json 时,我收到有关 json.
解码的错误有一种方法可以快速找出哪个字段有问题,而不是删除所有字段然后一个接一个地放回去找出哪个字段有问题。
如果您使用 Codable
来解析您的 JSON,您只需打印 error
在 catch
块中,它将打印问题所在位置的完整详细信息。
do {
let response = try JSONDecoder().decode(Root.self, from: data)
print(response)
} catch {
print(error) //here.....
}
只需在 catch
块中打印 error
实例(never error.localizedDescription
)。
错误显示 CodingPath
和发生错误的受影响的键。
您还可以添加额外的 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)
}