我知道我可以在Java中重新格式化JSON对象(使用Jackson,GSON等(。
{"a":"b", "c":"d"}
自
{
"a": "b",
"c": "d"
}
但是我如何将 JSON 对象转换回每行一个对象的格式,即我如何从
{
"a": "b",
"c": "d"
}
自
{"a":"b", "c":"d"}
在 Java 中使用现有的漂亮打印机?
看看下面的网址: 杰克逊序列化功能
这将向您展示如何禁用功能,例如每次调用的缩进输出,即使您重用已配置为漂亮打印的同一对象。
我认为Pretty Print是杰克逊1.x的命名法......你应该寻找SerializationFeature.INDENT_OUTPUT
@Test
public void test() throws Exception {
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String s = "{ "a" : "b" ,n "c" : "d"}";
Object x = mapper.readValue(s, Object.class);
ObjectWriter w = mapper.writer();
// Indented
System.out.println(w.writeValueAsString(x));
// Single Line
System.out.println(w.without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(x));
}
由于您已经在使用 Jackson,因此它应该使用:
String prettyJson = "{ "a" : "b" ,n "c" : "d"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode;
try {
jsonNode = objectMapper.readValue(prettyJson, JsonNode.class);
System.out.println(jsonNode.toString());
} catch (IOException e) {
e.printStackTrace();
}