漂亮地从Jackson 2.2的ObjectMapper中打印JSON

时间:2022-05-26 21:43:23

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:

现在我有一个org.fasterxml.jackson.databind的实例。ObjectMapper,并希望获得一个具有漂亮JSON的字符串。我搜索谷歌的所有结果都是关于Jackson 1的。x种方法,我似乎找不到合适的,不反对的方法,用2.2实现。尽管我不认为代码对于这个问题是绝对必要的,但我现在有以下几点:

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

7 个解决方案

#1


210  

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

您可以通过设置SerializationFeature来启用漂亮打印。在ObjectMapper上的INDENT_OUTPUT如下:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

#2


33  

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

根据mkyong的说法,神奇的咒语是把默认的打印写入到漂亮的打印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 gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Hope this helps...

希望这有助于……

#3


25  

The jackson API has changed:

杰克逊API已经改变:

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

#4


3  

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

IDENT_OUTPUT没有为我做任何事情,并给出一个与我的jackson 2.2.3 jar一起工作的完整答案:

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

#5


0  

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:

如果您想在进程中的所有ObjectMapper实例中默认打开这个选项,这里有一个小技巧,可以将INDENT_OUTPUT的默认值设置为true:

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

#6


0  

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.

如果你使用的是spring和jackson组合,你可以这样做。我按照建议使用@gregwhitaker,但使用spring风格实现。

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

#7


-7  

Try this.

试试这个。

 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

#1


210  

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

您可以通过设置SerializationFeature来启用漂亮打印。在ObjectMapper上的INDENT_OUTPUT如下:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

#2


33  

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

根据mkyong的说法,神奇的咒语是把默认的打印写入到漂亮的打印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 gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Hope this helps...

希望这有助于……

#3


25  

The jackson API has changed:

杰克逊API已经改变:

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

#4


3  

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

IDENT_OUTPUT没有为我做任何事情,并给出一个与我的jackson 2.2.3 jar一起工作的完整答案:

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

#5


0  

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:

如果您想在进程中的所有ObjectMapper实例中默认打开这个选项,这里有一个小技巧,可以将INDENT_OUTPUT的默认值设置为true:

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

#6


0  

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.

如果你使用的是spring和jackson组合,你可以这样做。我按照建议使用@gregwhitaker,但使用spring风格实现。

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

#7


-7  

Try this.

试试这个。

 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);