You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jackson序列化时移除key与冒号之间的空格?

解决Jackson序列化时键与冒号间多余空格的问题

要实现去掉键和冒号之间的空格同时保留缩进,直接调整Jackson的DefaultPrettyPrinter配置就行,不用复杂的自定义序列化器。

具体代码如下:

ObjectMapper mapper = new ObjectMapper();
// 初始化格式化打印机
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
// 将键值分隔符从默认的 ": " 改为 ":"
prettyPrinter.setObjectFieldValueSeparator(":");
// 设置缩进规则:用2个空格缩进,换行用\n
prettyPrinter.indentObjectsWith(new DefaultIndenter("  ", "\n"));
// 给ObjectMapper绑定这个自定义的打印机
mapper.setDefaultPrettyPrinter(prettyPrinter);

或者用更紧凑的链式写法:

ObjectMapper mapper = new ObjectMapper()
    .setDefaultPrettyPrinter(new DefaultPrettyPrinter()
        .setObjectFieldValueSeparator(":")
        .indentObjectsWith(new DefaultIndenter("  ", "\n")));

这样序列化出来的JSON就会是你想要的格式:

{
  "id": 2,
  "name": "theUser"
}

原理很简单:SerializationFeature.INDENT_OUTPUT本质是启用了默认的DefaultPrettyPrinter,而这个打印机默认会在冒号前加空格,我们只需要修改它的键值分隔符配置,就能在保留缩进的同时去掉多余空格。

内容的提问来源于stack exchange,提问作者jrao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:02:14