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');
}
}
}
-
\$\begingroup\$ This will be thrown off by any of the characters tested for occurring in a value string. \$\endgroup\$Cornelius Dol– Cornelius Dol2013年05月15日 00:58:48 +00:00Commented May 15, 2013 at 0:58
1 Answer 1
I think you need to ignore the contents of quoted values.
Add the flag:
boolean inQuotes=false;
then, at the top of your if
statement:
if (c == '"') {
inQuotes=!inQuotes;
}
if (!inQuotes) {
if (c == '{') {
sb.append(c);
sb.append(System.lineSeparator());
tabCount++;
printTabs(sb, tabCount);
} else if(c == '}') {
... // Your code
} else {
sb.append(c);
}
-
\$\begingroup\$ Aha, I knew I must've missed something. \$\endgroup\$durron597– durron5972013年05月15日 03:54:17 +00:00Commented May 15, 2013 at 3:54