我使用Jackson mapper版本2.6.5和Spring Boot,但我似乎可以让SerializationFeature.INDENT_OUTPUT
工作。我按照教程here进行了操作。我的代码如下。
public class SerializationExampleTreeModel {
public static void main(String[] args) throws IOException {
// Create the node factory that gives us nodes.
JsonNodeFactory nodeFactory = new JsonNodeFactory(false);
StringWriter stringWriter = new StringWriter();
// create a json factory to write the treenode as json. for the example
// we just write to console
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(stringWriter);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// the root node - album
JsonNode album = nodeFactory.objectNode();
album.put("Album-Title", "Kind Of Blue")
ArrayNode songs = nodeFactory.arrayNode()
songs.add("Song8").add("Song2")
album.put("Songs", songs)
ObjectNode artist = nodeFactory.objectNode()
artist.put("Name", "Alex" )
album.put( "artist", artist)
mapper.writeTree(generator, album)
println stringWriter.toString()
}
}
我总是得到结果:
{"Album-Title":"Kind Of Blue","Songs":["Song8","Song2"],"artist":{"Name":"Alex"}}
是否包含行mapper.configure(SerializationFeature.INDENT_OUTPUT, true)
。发生了什么事?
注意:我使用groovyc
编译我的代码,并且不需要使用分号。
答案 0 :(得分:0)
问题是您使用StringWriter
来编写输出,它会忽略您在ObjectMapper
上按预期设置的格式。相反,使用:
System.out.println(mapper.writeValueAsString(album));
如果您喜欢使用,可以在编写树之前声明打印机:
generator.setPrettyPrinter(new DefaultPrettyPrinter());
mapper.writeTree(generator, album);
这将允许正确的输出:
stringWriter.toString()