Sunday
18Oct2009
A good pretty-printer for Google Gson
Sunday, October 18, 2009 at 10:42AM I decided to do something about the one thing I wasn't happy about in Google Gson, the lack of good pretty-printing.
I created a class called GsonPrettyPrinter which outputs nice readable JSON in a reasonably intelligent way, you can grab the source code here.
Here is what the output looks like:
Note, in particular:
- Requires at least Gson 1.4 (the current version at the time of writing)
- It will try to represent JSON objects on arrays on a single line if it can
- It sorts JSON objects by their keys
- The code is in the public domain, with a request for attribution
Ian Clarke |
4 Comments | in
Java,
Programming
Java,
Programming 

Reader Comments (4)
The link to the source is broken :(
You are correct, I guess github deleted it because it was a "private" gist and was getting too much traffic.
I've replaced it with a public gist, so hopefully they won't do that again.
My apologies for barging in here, knowing nothing about any of this---and not belonging here at all. But I just wanted to say, Geewhiz! If I knew about all of this stuff, my hypergraphia could take off in an entirely new direction. Unfortunately, I don't induge mine. It indulges me a moment or two of calm every once in awhile. Oh well.
Thank you for this code! It's simple and gets the job done! You saved me a bunch of time!
I had to tweak it because we are currently using Gson 1.3, and I added a couple of ppJson() overloads, one that takes a JsonElement in case you already have one all parsed and one that takes a String with Json in it, and returns it pretty-printed. That's what I really needed was to reformat unformatted Json.
Besides the added methods, I modified the ppJson method that calls gson.toJsonTree() to construct a JsonElement. For Gson 1.3, you use gson to make the JSON string then you create a JsonElement from that. Below is the modified method and the two new overloads.
Thanks again!
public void ppJson(final Object o, final PrintWriter pw, Type t) {
final String jsonString = gson.toJson(o, t);
final JsonParser parser = new JsonParser();
final JsonElement jsonTree = parser.parse(jsonString);
final List<String> stringList = toStringList(jsonTree);
for (final String s : stringList) {
pw.println(s);
}
}
public String ppJson(final String jsonString) {
final JsonParser parser = new JsonParser();
final JsonElement jsonTree = parser.parse(jsonString);
final StringWriter sw = new StringWriter(128);
final PrintWriter pw = new PrintWriter(sw);
ppJson(jsonTree, pw);
return new String(sw.toString());
}
public void ppJson(final JsonElement jsonElement, final PrintWriter pw) {
final List<String> stringList = toStringList(jsonElement);
for (final String s : stringList) {
pw.println(s);
}
}