Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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');
        }
    }
}
share|improve this question
    
This will be thrown off by any of the characters tested for occurring in a value string. –  Lawrence Dol May 15 '13 at 0:58

1 Answer 1

up vote 2 down vote accepted

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);
        }
share|improve this answer
    
Aha, I knew I must've missed something. –  durron597 May 15 '13 at 3:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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