EN
Java json pretty print (Jackson library)
4 points
Quick solution:
xxxxxxxxxx
1
// import com.fasterxml.jackson.databind.ObjectMapper;
2
3
new ObjectMapper()
4
.writerWithDefaultPrettyPrinter() // <----- enable pretty print
5
.writeValueAsString(ourObject);
Output example:
xxxxxxxxxx
1
Normal json:
2
{"name":"john","age":23,"salary":5000,"skills":["java","js"]}
3
4
Pretty print:
5
{
6
"name" : "john",
7
"age" : 23,
8
"salary" : 5000,
9
"skills" : [ "java", "js" ]
10
}
xxxxxxxxxx
1
import com.fasterxml.jackson.core.JsonFactory;
2
import com.fasterxml.jackson.databind.JsonNode;
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
5
import java.io.IOException;
6
7
public class JavaJacksonPrettyPrint {
8
9
public static void main(String[] args) throws IOException {
10
11
String json = "{\"name\":\"john\",\"age\":23,\"salary\":5000,\"skills\":[\"java\",\"js\"]}";
12
System.out.println("Normal json:");
13
System.out.println(json);
14
System.out.println();
15
16
JsonNode rootNode = new ObjectMapper(new JsonFactory()).readTree(json);
17
ObjectMapper mapper = new ObjectMapper();
18
19
String prettyJson = mapper
20
.writerWithDefaultPrettyPrinter() // <----- enable pretty print
21
.writeValueAsString(rootNode);
22
23
System.out.println("Pretty print:");
24
System.out.println(prettyJson);
25
}
26
}
Output:
xxxxxxxxxx
1
Normal json:
2
{"name":"john","age":23,"salary":5000,"skills":["java","js"]}
3
4
Pretty print:
5
{
6
"name" : "john",
7
"age" : 23,
8
"salary" : 5000,
9
"skills" : [ "java", "js" ]
10
}
Hint: to know how to attach jackson
*.jar
lib to your project read this article.
Link to the library in the Maven repository:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind