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
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"
]
}
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());
}