Created
August 18, 2014 00:34
-
-
Save PaulBGD/6502f3cf7d3391cf8d73 to your computer and use it in GitHub Desktop.
Tidies up a JSON string in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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