JSON Beautifier Library for Java
I want to format a string containing JSON data using Java.开发者_Python百科 Does anybody know an open source library for that.
Assuming you're starting out with an existing JSON string, then Jackson can do this for you:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
String originalJson = ...
JsonNode tree = objectMapper .readTree(originalJson);
String formattedJson = objectMapper.writeValueAsString(tree);
Update to previous answer by skaffman, with newer versions of Jackson (2+, I think). The second line of code is now:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
With Jackson 2.6.1
String beautify(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(json, Object.class);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
Convert JSON String to Pretty Print JSON output using Jackson
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 :)
精彩评论