Jackson 2.15.2保存List为格式化JSON的格式问题求助
解决Jackson 2.15.2格式化List对象JSON格式不符预期的问题
要实现你想要的数组排版效果,需要自定义DefaultPrettyPrinter的数组输出规则——默认的writerWithDefaultPrettyPrinter()对数组的逻辑排版和你的预期不一致。
具体实现代码
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.DefaultIndenter; import com.fasterxml.jackson.databind.util.DefaultPrettyPrinter; import java.io.File; import java.io.IOException; import java.util.List; public class JsonListFormat { public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); // 自定义数组的起始、分隔、结束符排版逻辑 DefaultPrettyPrinter.DefaultArrayFormatter customArrayFormatter = new DefaultPrettyPrinter.DefaultArrayFormatter() { @Override public void writeArrayStart(JsonGenerator g) throws IOException { g.writeRaw("[\n"); // 数组起始符单独占一行 } @Override public void writeArraySeparator(JsonGenerator g) throws IOException { g.writeRaw(",\n"); // 元素分隔符后换行 } @Override public void writeArrayEnd(JsonGenerator g, int nrOfValues) throws IOException { g.writeRaw("\n]"); // 数组结束符单独占一行 } }; // 设置缩进规则:3个空格缩进(和你的预期格式匹配) DefaultIndenter customIndenter = new DefaultIndenter(" ", "\n"); // 组装自定义的PrettyPrinter DefaultPrettyPrinter customPrinter = new DefaultPrettyPrinter(); customPrinter.setArrayFormatter(customArrayFormatter); customPrinter.indentArraysWith(customIndenter); customPrinter.indentObjectsWith(customIndenter); // 测试用List对象 List<User> userList = List.of( new User("a", "a"), new User("b", "b"), new User("c", "c") ); // 写入JSON文件 mapper.writer(customPrinter).writeValue(new File("output.json"), userList); } // 示例实体类 static class User { private String firstName; private String lastName; public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } // 必须的Getter方法 public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } }
代码说明
- 数组排版定制:通过重写
DefaultArrayFormatter的三个方法,精准控制数组的起始符、元素分隔符、结束符的换行逻辑,让[和]各占一行,元素之间用逗号加换行分隔。 - 缩进规则匹配:用
DefaultIndenter设置元素缩进为3个空格,和你给出的预期格式完全对齐。 - 配置生效:将自定义的数组排版器和缩进规则绑定到
DefaultPrettyPrinter,替换默认的打印逻辑。
运行这段代码后,生成的JSON格式会完全符合你的预期。
内容的提问来源于stack exchange,提问作者Paul Marcelin Bejan
相关产品推荐
相关产品推荐

