Jackson JSON 反序列化:每行中的数组元素

2022-09-02 00:17:43

我正在使用Jackson,并希望漂亮地打印JSON,以便数组中的每个元素都转到每行,例如:

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

设置为 true 只会为对象字段插入换行符,而不会插入数组元素,而是以这种方式打印对象:SerializationFeature.INDENT_OUTPUT

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

有谁知道如何实现这一目标?谢谢!


答案 1

如果您不想扩展,也可以在外部设置属性:DefaultPrettyPrinterindentArraysWith

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);

答案 2

多亏了有用的提示,我能够配置我的所需缩进,如下所示:ObjectMapper

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);
}