[英]Pretty printing JSON from Jackson 2.2's ObjectMapper
现在我有一个org.fasterxml.jackson.databind.ObjectMapper
的实例,想要得到一个带有漂亮 JSON 的String
。 我的谷歌搜索的所有结果都提出了 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
您可以通过在ObjectMapper
上设置SerializationFeature.INDENT_OUTPUT
来启用漂亮打印,如下所示:
mapper.enable(SerializationFeature.INDENT_OUTPUT);
根据mkyong 的说法,魔法咒语是defaultPrintingWriter
来漂亮地打印 JSON :
较新的版本:
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));
旧版本:
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));
看来我跳得有点快。 您可以尝试gson ,其构造函数支持漂亮打印:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
希望这有助于...
杰克逊 API 已更改:
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());
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 ) );
}
如果你想默认为进程中的所有 ObjectMapper 实例打开它,这里有一个小技巧,将 INDENT_OUTPUT 的默认值设置为 true:
val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)
如果您使用的是 spring 和 jackson 组合,则可以按以下方式进行。 我按照建议遵循@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>
如果查看此问题的其他人只有一个 JSON 字符串(不在对象中),那么您可以将其放入HashMap
并仍然使ObjectMapper
工作。 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.