13

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.

Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46

3 Answers3

19

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)
}
grow4gaurav
  • 3,145
  • 1
  • 11
  • 12
18

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.....
}
PGDev
  • 23,751
  • 6
  • 34
  • 88
5

Just print the error instance (never error.localizedDescription) in the catch block.

The error displays the CodingPath and the affected key where the error occurs.

vadian
  • 274,689
  • 30
  • 353
  • 361