简体   繁体   English

来自 Jackson 2.2 的 ObjectMapper 的漂亮打印 JSON

[英]Pretty printing JSON from Jackson 2.2's ObjectMapper

Right now I have an instance of org.fasterxml.jackson.databind.ObjectMapper and would like to get a String with pretty JSON.现在我有一个org.fasterxml.jackson.databind.ObjectMapper的实例,想要得到一个带有漂亮 JSON 的String 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.我的谷歌搜索的所有结果都提出了 Jackson 1.x 这样做的方法,我似乎无法找到使用 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

您可以通过在ObjectMapper上设置SerializationFeature.INDENT_OUTPUT来启用漂亮打印,如下所示:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

According to mkyong , the magic incantation is defaultPrintingWriter to pretty print JSON :根据mkyong 的说法,魔法咒语是defaultPrintingWriter漂亮地打印 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...希望这有助于...

The jackson API has changed:杰克逊 API 已更改:

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: IDENT_OUTPUT 没有为我做任何事情,并给出一个适用于我的 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 ) );
}

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)

if you are using spring and jackson combination you can do it as following.如果您使用的是 spring 和 jackson 组合,则可以按以下方式进行。 I'm following @gregwhitaker as suggested but implementing in spring style.我按照建议遵循@gregwhitaker,但以春季风格实施。

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

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.如果查看此问题的其他人只有一个 JSON 字符串(不在对象中),那么您可以将其放入HashMap并仍然使ObjectMapper工作。 The result variable is your JSON string. result变量是您的 JSON 字符串。

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

试试这个。

 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM