有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    问题是您正在使用StringWriter写入输出,而它会忽略您在ObjectMapper上设置的格式,这与预期的一样。相反,请使用:

    System.out.println(mapper.writeValueAsString(album));
    

    如果您喜欢在使用时使用,您可以在编写树之前这样声明打印机:

    generator.setPrettyPrinter(new DefaultPrettyPrinter());
    mapper.writeTree(generator, album);
    

    这将允许正确的输出,包括:

    stringWriter.toString()