Jackson JSON Deserialization: array elements in each row

I am using Jackson and would like to print JSON nicely so that each element of the arrays falls into each line, for example:

  {
   "foo": "bar",
   "blah": [
     1,
     2
     3
   ]
 }

Setting SerializationFeature.INDENT_OUTPUT true only inserts newlines for the fields of the object, not the elements of the array, instead prints the object as follows:

  {
   "foo": "bar",
   "blah": [1, 2, 3]
 }

Does anyone know how to achieve this? Thanks!

+6
source share
5 answers

You can extend DefaultPrettyPrinter and override the beforeArrayValues ​​(...) and writeArrayValueSeparator (...) methods to archive the desired behavior. After that, you should add your new implementation to your JsonGenerator using setPrettyPrinter (...) .

+9
source

Thanks to helpful hints, I was able to customize my ObjectMapper with the desired indent as follows:

 private static class PrettyPrinter extends DefaultPrettyPrinter { public static final PrettyPrinter instance = new PrettyPrinter(); public PrettyPrinter() { _arrayIndenter = Lf2SpacesIndenter.instance; } } private static class Factory extends JsonFactory { @Override protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException { return super._createGenerator(out, ctxt).setPrettyPrinter(PrettyPrinter.instance); } } { ObjectMapper mapper = new ObjectMapper(new Factory()); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } 
+13
source

The answer , which is fortunately provided by the OP, shows a way to get a formatted JSON String with a single array based on the string from writeValueAsString . Based on this here, the solution is to write the same formatted JSON directly to a file with writeValue with less code:

 private static class PrettyPrinter extends DefaultPrettyPrinter { public static final PrettyPrinter instance = new PrettyPrinter(); public PrettyPrinter() { _arrayIndenter = Lf2SpacesIndenter.instance; } } { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(PrettyPrinter.instance); writer.writeValue(destFile, objectToSerialize); } 
+1
source

If you don't want to extend DefaultPrettyPrinter , you can also just set the indentArraysWith property from the outside:

 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(); prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance); String json = objectMapper.writer(prettyPrinter).writeValueAsString(object); 
+1
source

try JSON Generator ...

API reference
good example

0
source

All Articles