What is the simplest way to configure the indentation spacing on a Jackson ObjectMapper?

前端 未结 2 695
离开以前
离开以前 2021-01-03 20:39

I\'m really struggling with the degree of complexity I am perceiving in solving this problem. As the title says: What is a simple way to create a Jackson Objec

2条回答
  •  旧时难觅i
    2021-01-03 21:19

    I am not sure if this is the simplest way to go but... You can use the ObjectMapper with a custom printer. The DefaultPrettyPrinter can be used if you modify the indent behaviour.

    // Create the mapper
    ObjectMapper mapper = new ObjectMapper();
    
    // Setup a pretty printer with an indenter (indenter has 4 spaces in this case)
    DefaultPrettyPrinter.Indenter indenter = 
            new DefaultIndenter("    ", DefaultIndenter.SYS_LF);
    DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
    printer.indentObjectsWith(indenter);
    printer.indentArraysWith(indenter);
    
    // Some object to serialize
    Map value = new HashMap<>();
    value.put("foo", Arrays.asList("a", "b", "c"));
    
    // Serialize it using the custom printer
    String json = mapper.writer(printer).writeValueAsString(value);
    
    // Print it
    System.out.println(json);
    

    The output will be:

    {
        "foo" : [
            "a",
            "b",
            "c"
        ]
    }
    

提交回复
热议问题