Android JSON: How to print a JSON string in a human-readable format (for debugging)

Android JSON tip: How to use the JSONObject toString(n) method to debug a JSON string in an Android app, by printing the string in a human-readable format.

While working on an Android project recently, I noticed there is a toString method on a JSONObject object that looks like this:


It turns out that this toString method prints the current JSONObject in a nice human-readable format. I used that functionality in the following code to print a formatted JSON string into an Android TextView object so I could see what I was working with:

JSONObject jsonObject = (new JSONObject(response)).getJSONObject("");

I'm sorry I don't have any printed output to share with you, but if you've ever looked at a JSON response from a web service like Twitter, you know it's not in a human-readable format by default; all the characters just run together in a format only a machine could love.

So, whenever you see that problem in your Android JSON code, just remember this toString method debugging approach. (As Adrian Monk would say, you'll thank me later. :)