Skip to content

Instantly share code, notes, and snippets.

@PaulBGD
Created August 18, 2014 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulBGD/6502f3cf7d3391cf8d73 to your computer and use it in GitHub Desktop.
Save PaulBGD/6502f3cf7d3391cf8d73 to your computer and use it in GitHub Desktop.
Tidies up a JSON string in Java
package me.paulbgd.bgdcore.json;
public class JSONTidier {
private static final String tab = "\t";
private static final String line = "\n";
public static String tidyJSON(String json) {
StringBuilder string = new StringBuilder();
int tabCount = 0;
boolean quotes = false;
char[] charArray = json.toCharArray();
for (int i = 0, charArrayLength = charArray.length; i < charArrayLength; i++) {
char c = charArray[i];
if (c == '"' && i != 0 && charArray[i - 1] != '\\') {
quotes = !quotes;
}
if (quotes) {
string.append(c);
continue;
}
switch (c) {
case '{':
case '[':
string.append(c).append(line);
tabCount++;
for (int j = 0; j < tabCount; j++) {
string.append(tab);
}
break;
case '}':
case ']':
string.append(line);
tabCount--;
for (int j = 0; j < tabCount; j++) {
string.append(tab);
}
string.append(c);
break;
case ',':
string.append(c);
if (i + 1 != charArrayLength && charArray[i + 1] != '{' && charArray[i + 1] != '[') {
string.append(line);
for (int j = 0; j < tabCount; j++) {
string.append(tab);
}
}
break;
case ':':
string.append(c).append(" ");
break;
default:
string.append(c);
break;
}
}
return string.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment