Skip to content

Instantly share code, notes, and snippets.

@sanity
Created September 22, 2009 13:31
Show Gist options
  • Save sanity/191066 to your computer and use it in GitHub Desktop.
Save sanity/191066 to your computer and use it in GitHub Desktop.
final String json = gson.toJson(o);
final StringBuilder pretty = new StringBuilder();
String indent = "";
char p = '\b';
boolean in = false;
for (final char c : json.toCharArray()) {
if (c == '"') {
in = !in;
}
if (in) {
pretty.append(c);
} else if (!Character.isWhitespace(c)) {
if (c == '{') {
if (p != ',' && pretty.length() > 0) {
pretty.append('\n').append(indent);
}
indent += " ";
pretty.append(c).append('\n').append(indent);
} else if (c == '}') {
if (indent.length() > 0) {
indent = indent.substring(2);
}
pretty.append("\n").append(indent).append(c);
} else if (c == ',') {
pretty.append(c).append('\n').append(indent);
} else if (c == ':') {
pretty.append(" : ");
} else {
pretty.append(c);
}
}
p = c;
}
return pretty.toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment