I want to format a string containing JSON data using Java. Does anybody know an open source library for that.
I made a simple code can do this, you just need to create a new class call BeautifulJson
and paste all of them in.
public class BeautifulJson {
public static String beautiful(String input) {
int tabCount = 0;
StringBuilder inputBuilder = new StringBuilder();
char[] inputChar = input.toCharArray();
for (int i = 0; i < inputChar.length; i++) {
String charI = String.valueOf(inputChar[i]);
if (charI.equals("}") || charI.equals("]")) {
tabCount--;
if (!String.valueOf(inputChar[i - 1]).equals("[") && !String.valueOf(inputChar[i - 1]).equals("{"))
inputBuilder.append(newLine(tabCount));
}
inputBuilder.append(charI);
if (charI.equals("{") || charI.equals("[")) {
tabCount++;
if (String.valueOf(inputChar[i + 1]).equals("]") || String.valueOf(inputChar[i + 1]).equals("}"))
continue;
inputBuilder.append(newLine(tabCount));
}
if (charI.equals(",")) {
inputBuilder.append(newLine(tabCount));
}
}
return inputBuilder.toString();
}
private static String newLine(int tabCount) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
for (int j = 0; j < tabCount; j++)
builder.append(" ");
return builder.toString();
}
}
To use this:
String beautifulJson = BeautifulJson.beautiful("JSON in string");
Example:
static String json = "{\"success\": true,\"metadata\": {\"transactionId\": 0,\"status_code\": 0},\"errors\": [{\"code\": \"string\",\"message\": \"string\"}]}";
public static void main(String[] args) {
//Original JSON
System.out.println(json);
//beautiful JSON
System.out.println(beautiful(json));
}
This is my first post on stack overflow :)