Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON Deserialization: array elements in each line

I am using Jackson and would like to pretty-print JSON such that each element in arrays goes to each line, like:

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

Setting SerializationFeature.INDENT_OUTPUT true only inserts newline characters for object fields, not array elements, printing the object in this way instead:

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

Does anyone know how to achieve this? Thanks!

like image 663
lyomi Avatar asked Feb 18 '13 14:02

lyomi


2 Answers

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

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);

String json = objectMapper.writer(prettyPrinter).writeValueAsString(object);
like image 136
Stefan Haberl Avatar answered Nov 20 '22 04:11

Stefan Haberl


Thanks to the helpful hints, I was able to configure my ObjectMapper with desired indentation 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);
}
like image 17
lyomi Avatar answered Nov 20 '22 02:11

lyomi