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

前端 未结 2 696
离开以前
离开以前 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条回答
  • 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<String, Object> 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"
        ]
    }
    
    0 讨论(0)
  • 2021-01-03 21:24

    If you intend to write multiple objects, as I did, to get JSON comparison in a JUnit test running in IntelliJ (which has a very nice multiline compare tool):

    // could likely be simplified to `new ObjectMapper().writer(new DefaultPrettyPrinter())`
    ObjectWriter writer = new ObjectMapper()
            .setDefaultPrettyPrinter(new DefaultPrettyPrinter())
            .writerWithDefaultPrettyPrinter();
    
    try {
        String expected = writer.writeValueAsString(testCase.getThing());
        String actual = writer.writeValueAsString(actual.getThing());
        assertEquals(expected, actual);
    } catch (JsonProcessingException e) {
        fail("JSON exception: " + e.toString());
    }
    
    0 讨论(0)
提交回复
热议问题