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)
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |