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

Java使用SnakeYaml递归获取Yaml全路径键丢失前缀如何解决

核心问题原因

你的代码存在两个核心错误:

  1. 使用static静态变量存储keys和path,不仅会导致多次实例化YamlKeys时数据互相污染,还会让递归过程中的路径状态全局共享,容易出现层级混乱。
  2. 遍历完当前层级的所有key后直接执行path = ""清空全路径,导致处理完AnotherKey节点回到SecondKey层级时,路径已经被清空,后续拼接TestKey时就丢失了前面的FirstKey.SecondKey前缀。

修复方案

将路径改为递归方法的入参传递,每层递归的路径独立存储,不需要手动维护路径回退逻辑,天然符合递归的层级特性,修复后的代码如下:

public class YamlKeys {
    // 改为实例变量,避免多次实例化数据污染
    private Set<String> keys = new HashSet<>();

    YamlKeys(Map<?, ?> data) {
        // 初始路径为空串传入递归方法
        getKeysRecursive(data, "");
    }

    private void getKeysRecursive(final Map<?, ?> data, String currentPath) {
        for(Object key : data.keySet()) {
            // 非字符串类型key直接跳过
            if(!(key instanceof String)) {
                continue;
            }
            String strKey = (String) key;
            // 拼接当前层级路径,上层路径不受影响
            String newPath = currentPath.isEmpty() ? strKey : currentPath + "." + strKey;
            Object value = data.get(key);
            if(value instanceof Map) {
                // 下一层递归直接传入拼接好的新路径
                getKeysRecursive((Map<?, ?>) value, newPath);
            } else {
                // 叶子节点直接存入结果集
                keys.add(newPath);
            }
        }
    }

    Set<String> getKeys() {
        return keys;
    }
}

效果验证

用你提供的yaml文件测试,输出结果如下,完全符合预期:

FirstKey.SecondKey.AnotherKey.AValue
FirstKey.SecondKey.Enabled
FirstKey.SecondKey.ID
FirstKey.SecondKey.TestKey.TestValue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 16:27:03