由于 Dany 的回答对我不起作用,我想像 yaml 解析一样支持 Spring Boot,这是我的解决方案:
Map expandMapKeys(Map source) {
source.inject([:]) { result, key, value ->
if (value instanceof Map) value = expandMapKeys(value)
result + key.tokenize('.').reverse().inject(value) { current, token ->
[(token): current]
}
}
}
assert expandMapKeys([a: 'b']) == [a: 'b']
assert expandMapKeys([a: [b: 'c']]) == [a: [b: 'c']]
assert expandMapKeys(['a.b': 'c']) == [a: [b: 'c']]
assert expandMapKeys([a: ['b.c.d': 'e']]) == [a: [b: [c: [d: 'e']]]]
assert expandMapKeys(['a.b': 'c', 'a.d': 'e']) == [a: [d: 'e']] // not [a: [b: 'c', d: 'e'] !
注意最后一个断言:相同的父映射键将被覆盖。为了解决这个问题,我们需要使用深度合并(我在互联网上找到的)。此外,我们将处理一级列表,因为它们也可以在 yaml 中使用:
Map expandMapKeys(Map source) {
source.inject([:]) { result, key, value ->
if (value instanceof Map) value = expandMapKeys(value)
if (value instanceof Collection) value = value.collect { it instanceof Map ? expandMapKeys(it) : it }
merge(result, key.tokenize('.').reverse().inject(value) { current, token ->
[(token): current]
})
}
}
Map merge(Map[] sources) {
if (!sources) return [:]
if (sources.length == 1) return sources[0]
sources.inject([:]) { result, map ->
map.each { key, value ->
result[key] = result[key] instanceof Map ? merge(result[key], value) : value
}
result
}
}
assert expandMapKeys([a: 'b']) == [a: 'b']
assert expandMapKeys([a: [b: 'c']]) == [a: [b: 'c']]
assert expandMapKeys(['a.b': 'c']) == [a: [b: 'c']]
assert expandMapKeys([a: ['b.c.d': 'e']]) == [a: [b: [c: [d: 'e']]]]
assert expandMapKeys(['a.b': 'c', 'a.d': 'e']) == [a: [b: 'c', d: 'e']]
assert expandMapKeys([a: ['b.c': 'd'], e: [[f: ['g.h': 'i']], [j: ['k.l': 'm']]]]) == [a: [b: [c: 'd']], e: [[f: [g: [h: 'i']]], [j: [k: [l: 'm']]]]]