How to debug your JSON in Xcode when JSONDecoder fails
Sometimes, JSONDecoder fails. And when that happens, it can be difficult to figure out what went wrong. Not if you can print Data instances!
Sometimes, Xcode doesn't help us as much as we'd like. When it comes to networking and JSON, for example.
I think we (iOS Developers) have all been there. You've setup your DTOs and / or models, preferably implementing the Codable protocol, and all your endpoints are configured. Possibly via Alamofire, Moya, or some "good old" NSURLSessions.
You run the app. Nothing shows up in the collection view.
You check the items you're trying to load into it. Nothing. Empty. Maybe even nil. An error perhaps shows up in the console if you handled it right. But that's all there is.
You put a breakpoint in your network layer. Run it again. It stops. The call itself has succeeded. Still, nothing shows up.
The JSON decoding failed.
The first few times, you tried setting up a breakpoint, or perhaps a print
, just before the offending call to JSONDecoder().decode(_:from:)
. Alas, printing a Data
object is useless.
Well, no more! Today, I shall grant you the awesome power of Data
printing! Set your breakpoint, and when you reach it and the debugger pauses, write down this magical incantation in the console:
po String(data: yourDataVariable as! Data, encoding: String.Encoding.utf8)
You could also set it as the breakpoint's command, but it has been a hit & miss for me so far, and breakpoint commands appear to somehow be quite slow to execute.
Yes, that's it. That's all there is to it. Thank you, StackOverflow. Now, combine it with this glorious debugging trick from Natasha The Robot (via The Wayback Machine, since the original link is down), and you're set to go and fight off those villainous obscure bugs! And if you want to take it even further, here's how to create an alias for printing dictionaries as formated json.
If you have any feedback, question, or a differing opinion on how it should be, please feel free to let me know on Twitter!
Comments ()