GenuineSounds

Untitled

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