Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty printing JSON from Jackson 2.2's ObjectMapper

Tags:

java

json

jackson

People also ask

How do I enable pretty print JSON?

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.

How do I read JSON file with ObjectMapper?

Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);

Is ObjectMapper thread-safe Jackson?

Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.


You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT on your ObjectMapper like so:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

According to mkyong, the magic incantation is defaultPrintingWriter to pretty print JSON:

Newer versions:

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));

Older versions:

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));

Seems I jumped the gun a tad quickly. You could try gson, whose constructor supports pretty-printing:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Hope this helps...


The jackson API has changed:

new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());

the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:

public static void main(String[] args) throws IOException {

byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));

ObjectMapper objectMapper = new ObjectMapper();

Object json = objectMapper.readValue( jsonBytes, Object.class );

System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}