GenuineSounds

JSON Formatter

Jan 12th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. public static String format(String input) {
  2.     int tabs = 0;
  3.     boolean quoted = false;
  4.     StringBuilder builder = new StringBuilder(input);
  5.     for (int index = 0; index < builder.length(); index++) {
  6.         char c = builder.charAt(index);
  7.         if (quoted && c != '"')
  8.             continue;
  9.         switch (c) {
  10.             case '"':
  11.                 quoted = !(quoted && builder.charAt(index - 1) != '\\');
  12.                 continue;
  13.             case ':':
  14.                 builder.insert(++index, ' ');
  15.                 continue;
  16.             case '{':
  17.             case '[':
  18.                 tabs++;
  19.             case ',':
  20.                 builder.insert(index + 1, '\n');
  21.                 continue;
  22.             case '}':
  23.             case ']':
  24.                 tabs--;
  25.                 builder.insert(index++, '\n');
  26.                 for (int t = 0; t < tabs; t++)
  27.                     builder.insert(index++, '\t');
  28.                 continue;
  29.             case '\n':
  30.                 for (int t = 0; t < tabs; t++)
  31.                     builder.insert(++index, '\t');
  32.                 continue;
  33.         }
  34.     }
  35.     return builder.toString();
  36. }
Add Comment
Please, Sign In to add comment