You need to enable JavaScript to run this app. 如何使用Jackson和ObjectMapper将层级分隔键扁平Map转为嵌套JSON
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jackson和ObjectMapper将层级分隔键扁平Map转为嵌套JSON

实现可行性说明

完全可以基于Jackson与ObjectMapper API实现两类层级分隔扁平Map到嵌套JSON的转换。

Jackson的基础序列化能力虽然不原生支持自动拆分带分隔符的层级键,但我们可以借助其内置的ObjectNode、JsonNode原生数据结构API,搭配通用的层级键拆分逻辑完成转换,不需要引入第三方扩展组件,实现逻辑和你找到的JavaScript同类方案完全对齐。

核心实现逻辑

整体流程和JS版本的拆分逻辑保持一致:

  • 以Jackson的ObjectNode作为嵌套JSON结构的根载体
  • 遍历扁平Map的每一个键值对
  • 按照对应分隔符(点/斜杠)拆分层级键,过滤拆分产生的无效空段
  • 从根节点开始逐层向下查找、创建对应的嵌套对象节点
  • 到达键的最后一层时,将原始值写入对应叶子节点
  • 最终将构建完成的ObjectNode通过ObjectMapper序列化为目标结构JSON
完整可运行实现代码

代码仅依赖Jackson核心包jackson-databind,可直接兼容点分隔、斜杠路径分隔两类键格式:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class FlatMapToNestedJsonConverter {
    private final ObjectMapper objectMapper;

    public FlatMapToNestedJsonConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 将扁平Map转换为嵌套JSON结构
     * @param flatMap 带层级分隔键的扁平Map
     * @param splitRegex 层级键的拆分正则,点分隔传入"\\.",斜杠分隔传入"/"
     * @return 嵌套结构的JsonNode
     */
    public JsonNode convert(Map<String, Object> flatMap, String splitRegex) {
        ObjectNode rootNode = objectMapper.createObjectNode();

        for (Map.Entry<String, Object> entry : flatMap.entrySet()) {
            String[] keyParts = entry.getKey().split(splitRegex);
            // 过滤拆分后产生的空字符串(如斜杠开头的键拆分后首元素为空)
            String[] filteredParts = Arrays.stream(keyParts)
                    .filter(part -> !part.isBlank())
                    .collect(Collectors.toList())
                    .toArray(new String[0]);

            ObjectNode currentNode = rootNode;
            // 遍历到倒数第二层,提前创建缺失的嵌套对象
            for (int i = 0; i < filteredParts.length - 1; i++) {
                String part = filteredParts[i];
                if (!currentNode.has(part)) {
                    currentNode.setObject(part);
                }
                currentNode = (ObjectNode) currentNode.get(part);
            }
            // 在最后一层写入实际值
            String lastKey = filteredParts[filteredParts.length - 1];
            currentNode.set(lastKey, objectMapper.valueToTree(entry.getValue()));
        }
        return rootNode;
    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        FlatMapToNestedJsonConverter converter = new FlatMapToNestedJsonConverter(mapper);

        // 测试点分隔键场景
        Map<String, Object> dotKeyMap = Map.of(
                "media.video.one", "hello",
                "media.video.two", "world",
                "media.audio.one", "hi"
        );
        JsonNode dotResult = converter.convert(dotKeyMap, "\\.");
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dotResult));

        // 测试斜杠路径键场景
        Map<String, Object> slashKeyMap = Map.of(
                "/media/video/one", "hello",
                "/media/video/two", "world",
                "/media/audio/one", "hi"
        );
        JsonNode slashResult = converter.convert(slashKeyMap, "/");
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(slashResult));
    }
}
关键注意事项
  • 分隔符适配:Java的字符串split方法入参为正则表达式,点号.是正则元字符,传入时需要写为转义形式"\\.",否则拆分逻辑会完全失效;斜杠/无正则特殊含义,可直接传入使用
  • 边界处理:以斜杠开头的路径键拆分后会在数组首位生成空字符串元素,需要做过滤处理,避免在根节点下生成空键的无效结构
  • 值类型兼容:通过objectMapper.valueToTree()可以自动兼容字符串、数字、布尔、自定义复杂对象等任意类型的value,不需要针对不同值类型做额外转换
  • 输出格式:可以通过writerWithDefaultPrettyPrinter()开启缩进格式化输出,生成和示例一致的可读JSON结构
  • 示例笔误提示:你提供的目标JSON中存在两处笔误:"auido"应为"audio",video.two的取值应为原始Map对应的"world",上述代码的转换结果会输出正确的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 03:24:06