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');
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ This will be thrown off by any of the characters tested for occurring in a value string. \$\endgroup\$ 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);
        }
\$\endgroup\$
1
  • \$\begingroup\$ Aha, I knew I must've missed something. \$\endgroup\$
    – durron597
    May 15, 2013 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.