Skip to content

Instantly share code, notes, and snippets.

@keweishang
Created April 9, 2018 13:16
Show Gist options
  • Save keweishang/c08dd87f3529977773b362747a64bba0 to your computer and use it in GitHub Desktop.
Save keweishang/c08dd87f3529977773b362747a64bba0 to your computer and use it in GitHub Desktop.
My stupid JsonFormatter
/**
* Format a JSON string and make it more readable
* Created by kshang on 20/04/2017.
*/
public class JsonFormatter {
public String format(String input) {
StringBuilder sb = new StringBuilder();
char[] chars = input.toCharArray();
boolean inQuote = false;
boolean newLine = true;
int level = 0;
Character close = null;
for (int i = 0; i < chars.length; i++) {
// Ignore white spaces
if (!inQuote && Character.isWhitespace(chars[i])) continue;
// Indentation for new line
if (newLine) {
newLine = false;
for (int j = 0; j < level; j++) {
sb.append('\t');
}
}
if (close != null) {
sb.append(close);
close = null;
}
switch (chars[i]) {
// break line
case ',':
sb.append(chars[i]);
if (!inQuote) {
sb.append("\n");
newLine = true;
}
break;
// check whether inQuote
case '"':
sb.append(chars[i]);
inQuote = !inQuote;
break;
// object or array, add increment indentation
case '[':
case '{':
sb.append(chars[i]);
if (!inQuote) {
sb.append("\n");
newLine = true;
level++;
}
break;
case ']':
case '}':
// buffer the close bracket and curly brace
close = chars[i];
if (!inQuote) {
sb.append("\n");
newLine = true;
level--;
}
break;
default:
sb.append(chars[i]);
}
}
// last close bracket or curly brace
if (close != null) {
sb.append(close);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment