GenuineSounds icon

Untitled

GenuineSounds | PRO | 01/12/16 03:32:12 PM UTC | 0 ⭐ | 375 👁️ | Never ⏰ | []
Java |

960 B

|

None

|

0 👍

/

0 👎

// Cleanup white-space beforehand.
public static String formatJSON(String input) {
    int tabs = 0;
    boolean quoted = false;
    StringBuilder builder = new StringBuilder(input);
    for (int index = 0; index < builder.length(); index++) {
        char c = builder.charAt(index);
        switch (c) {
            case '"':
                if (quoted && builder.charAt(index - 1) != '\\')
                    quoted = false;
                else
                    quoted = true;
                break;
            case '{':
            case '[':
                tabs++;
                builder.insert(index + 1, '\n');
                break;
            case '}':
            case ']':
                tabs--;
                builder.insert(index++, '\n');
                for (int t = 0; t < tabs; t++)
                    builder.insert(index++, '\t');
                break;
            case ':':
                builder.insert(index++, ' ');
                builder.insert(index++ + 1, ' ');
                break;
            case ',':
                builder.insert(index + 1, '\n');
                break;
            case '\n':
                for (int t = 0; t < tabs; t++)
                    builder.insert(++index, '\t');
                break;
        }
    }
    return builder.toString();
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎