Pretty printing JSON from Jackson 2.2's ObjectMapper

JavaJsonJackson

Java Problem Overview


Right now I have an instance of org.fasterxml.jackson.databind.ObjectMapper and would like to get a String with pretty JSON. All of the results of my Google searches have come up with Jackson 1.x ways of doing this and I can't seem to find the proper, non-deprecated way of doing this with 2.2. Even though I don't believe that code is absolutely necessary for this question, here's what I have right now:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println("\n\n----------REQUEST-----------");
StringWriter sw = new StringWriter();
mapper.writeValue(sw, jsonObject);
// Want pretty version of sw.toString() here

Java Solutions


Solution 1 - Java

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

mapper.enable(SerializationFeature.INDENT_OUTPUT);

Solution 2 - Java

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...

Solution 3 - Java

The jackson API has changed:

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

Solution 4 - Java

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 ) );
}

Solution 5 - Java

If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:

val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)

Solution 6 - Java

if you are using spring and jackson combination you can do it as following. I'm following @gregwhitaker as suggested but implementing in spring style.

<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
	<property name="dateFormat">
		<bean class="java.text.SimpleDateFormat">
			<constructor-arg value="yyyy-MM-dd" />
			<property name="lenient" value="false" />
		</bean>
	</property>
	<property name="serializationInclusion">
		<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
			NON_NULL
		</value>
	</property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
	<property name="targetObject">
		<ref bean="objectMapper" />
	</property>
	<property name="targetMethod">
		<value>enable</value>
	</property>
	<property name="arguments">
		<value type="com.fasterxml.jackson.databind.SerializationFeature">
			INDENT_OUTPUT
		</value>
	</property>
</bean>

Solution 7 - Java

If others who view this question only have a JSON string (not in an object), then you can put it into a HashMap and still get the ObjectMapper to work. The result variable is your JSON string.

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

// Pretty-print the JSON result
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

Solution 8 - Java

Try this.

 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony AtkinsonView Question on Stackoverflow
Solution 1 - JavagregwhitakerView Answer on Stackoverflow
Solution 2 - Javahd1View Answer on Stackoverflow
Solution 3 - JavaRianView Answer on Stackoverflow
Solution 4 - JavaStan TowianskiView Answer on Stackoverflow
Solution 5 - JavaGraham LeaView Answer on Stackoverflow
Solution 6 - JavaMohanaRao SVView Answer on Stackoverflow
Solution 7 - JavaAzurespotView Answer on Stackoverflow
Solution 8 - JavaNagappa L MView Answer on Stackoverflow