I couldn't quickly find Java code with googling to make serialized Json easier to read (this is a debugging library, obviously implementation code wouldn't use this as it's just more characters). This is not intended to be viewed in a web browser, this is intended for console output mostly. I'm fairly new to Json (that's probably why I don't know where to look for this), is there a use case that my code is missing?
public class JsonWhitespace {
public static String toWhiteSpace(String noWhite) {
StringBuilder sb = new StringBuilder();
int tabCount = 0;
boolean inArray = false;
for(char c : noWhite.toCharArray()) {
if (c == '{') {
sb.append(c);
sb.append(System.lineSeparator());
tabCount++;
printTabs(sb, tabCount);
} else if(c == '}') {
sb.append(System.lineSeparator());
tabCount--;
printTabs(sb, tabCount);
sb.append(c);
} else if(c == ',') {
sb.append(c);
if (!inArray) {
sb.append(System.lineSeparator());
printTabs(sb, tabCount);
}
} else if (c == '[') {
sb.append(c);
inArray = true;
} else if (c == ']') {
sb.append(c);
inArray = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
private static void printTabs(StringBuilder sb, int tabCount) {
for(int i = 0; i < tabCount; i++) {
sb.append('\t');
}
}
}