java序列化功能。Jackson 2.6.5上的缩进输出被忽略
我正在使用带Spring Boot的Jackson mapper 2.6.5版,但我似乎可以SerializationFeature.INDENT_OUTPUT
工作。我正在学习教程。我的代码如下
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
编译代码,不需要分号
# 1 楼答案
问题是您正在使用
StringWriter
写入输出,而它会忽略您在ObjectMapper
上设置的格式,这与预期的一样。相反,请使用:如果您喜欢在使用时使用,您可以在编写树之前这样声明打印机:
这将允许正确的输出,包括: