2
\$\begingroup\$

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');
 }
 }
}
asked May 14, 2013 at 21:25
\$\endgroup\$
1
  • \$\begingroup\$ This will be thrown off by any of the characters tested for occurring in a value string. \$\endgroup\$ Commented May 15, 2013 at 0:58

1 Answer 1

2
\$\begingroup\$

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);
 }
durron597
9489 silver badges24 bronze badges
answered May 15, 2013 at 1:01
\$\endgroup\$
1
  • \$\begingroup\$ Aha, I knew I must've missed something. \$\endgroup\$ Commented May 15, 2013 at 3:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.