The following example demonstrates how to pretty print the JSON string produces by Jackson library. To produce well formatted JSON string we create the ObjectMapper
instance and enable the SerializationFeature.INDENT_OUTPUT
feature. To enable this feature we need to call the enable()
method of the ObjectMapper
and provide the feature to be enabled.
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(recording);
System.out.println(json);
On the second example below we format unformatted JSON string. To do this we use the ObjectMapper
‘s readValue(String, Class<T>)
method which accept the JSON string and Object.class
as the value type. The readValue()
method return an Object
. To format the JSON object we call mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Object)
. This will produce a pretty formatted JSON.
ObjectMapper mapper = new ObjectMapper();
Object jsonObject = mapper.readValue(json, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);
Below is the complete code snippets.
package org.kodejava.jackson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.kodejava.jackson.support.Artist;
import org.kodejava.jackson.support.Label;
import org.kodejava.jackson.support.Recording;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Month;
public class JsonIndentOutput {
public static void main(String[] args) {
JsonIndentOutput.formatObjectToJsonString();
JsonIndentOutput.formatJsonString();
}
private static void formatObjectToJsonString() {
Recording recording = new Recording();
recording.setId(1L);
recording.setTitle("Yellow Submarine");
recording.setReleaseDate(LocalDate.of(1969, Month.JANUARY, 17));
recording.setArtist(new Artist(1L, "The Beatles"));
recording.setLabel(new Label(1L, "Apple"));
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
try {
String json = mapper.writeValueAsString(recording);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
private static void formatJsonString() {
String json = """
{"id":1,"title":"Yellow Submarine","releaseDate":"1969-01-17","artist":{"id":1,"name":"The Beatles"},"label":{"id":1,"name":"Apple"}}
""";
ObjectMapper mapper = new ObjectMapper();
try {
Object jsonObject = mapper.readValue(json, Object.class);
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(prettyJson);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code snippet above will pretty print the following JSON string:
{
"id" : 1,
"title" : "Yellow Submarine",
"releaseDate" : "1969-01-17",
"artist" : {
"id" : 1,
"name" : "The Beatles"
},
"label" : {
"id" : 1,
"name" : "Apple"
}
}
Here are the structure of Recording
, Artist
and Label
classes.
package org.kodejava.jackson.support;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.kodejava.jackson.LocalDateDeserializer;
import org.kodejava.jackson.LocalDateSerializer;
import java.time.LocalDate;
public class Recording {
private Long id;
private String title;
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate releaseDate;
private Artist artist;
private Label label;
// Getters and Setters
}
package org.kodejava.jackson.support;
public class Artist {
private Long id;
private String name;
public Artist() {
}
public Artist(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters and Setters
}
package org.kodejava.jackson.support;
public class Label {
private Long id;
private String title;
public Label(Long id, String title) {
this.id = id;
this.title = title;
}
// Getters and Setters
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Very nice article , sometime I use https://jsonformatter.org/json-pretty-print or https://codebeautify.org/jsonviewer to make it pretty.
Great tutorial! Check this tool also: json formatter https://jsonformatter-online.com
Hi! I have a GREAT problem with Jackson. Anyone knows how to transform JSON into Array?
Hi Leonardo,
To convert JSON to Array you code do something like:
When I write it to a file the indentation is converted to
\r\
.Hi Deepraj, can you show the code?