Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: There is way to debug decodable object quickly

I have an object from 20 fields. When I get the json from the server I get an error about the decode of the json.

There is a way to quickly find out which field is problematic instead of deleting all the fields and putting it back one after the other to find out which one is problematic.

like image 578
Mickael Belhassen Avatar asked Jan 22 '20 07:01

Mickael Belhassen


2 Answers

If you're using Codable to parse your JSON, you can simply print the error in catch block and it will print the complete details of where the issue exist.

do {
    let response = try JSONDecoder().decode(Root.self, from: data)
    print(response)
} catch {
    print(error) //here.....
}
like image 131
PGDev Avatar answered Nov 09 '22 14:11

PGDev


You can also add additional catch blocks to understand exactly what is the nature of the error.

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)
}
like image 13
grow4gaurav Avatar answered Nov 09 '22 15:11

grow4gaurav