Groovy地图点键嵌入地图 [英] Groovy map dot keys to nested map

查看:104
本文介绍了Groovy地图点键嵌入地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  [test.key] 

我有一个带有点符号的地图,但我需要它作为一个嵌套的地图。 .one:'value1',text.key.two:'value2']



$ b

  [
test:[
key:[
one:'value1'
二:'value2'
]
]
]

这里是我的代码的想法

  def extract(String key,String value){

if(key.contains(。)){
def(String target,String subKey)= key.split('\\。',2)
return [$ target :extract(subKey,value)]
} else {
return [$ key:extractType(value)]
}

}

但是,我想知道在关闭中是否有任何神奇的魔法,或者帮助其他好玩的东西,它更简单。

解决方案

Th ere是一个方便的课程: groovy.util.ConfigSlurper

  def map = ['test.key.one':'value1','test.key.two':'value2'] 
def props = new Properties()
props.putAll(map)
println new ConfigSlurper()。parse(props)// [test:[key:[two:value2,one:value1]]]

唯一的缺点是它需要 java.util.Properties 实例,因此您需要从地图


I have a map with keys in dot notation, but I need it as a nested map.

[test.key.one: 'value1', text.key.two: 'value2']

Now the result should be

[
    test: [
        key: [
            one: 'value1',
            two: 'value2'
        ]
    ]
]

And here is my idea of code

def extract(String key, String value) {

    if(key.contains(".")) {
        def (String target, String subKey) = key.split('\\.', 2)
        return ["$target": extract(subKey, value)]
    } else {
        return ["$key": extractType(value)]
    }

}

But I want to know if there is any groovy magic doing this in a closure or witht he help of other goodies to make it simpler.

解决方案

There is one handy class: groovy.util.ConfigSlurper

def map = ['test.key.one': 'value1', 'test.key.two': 'value2']
def props = new Properties()
props.putAll(map)
println new ConfigSlurper().parse(props) // [test:[key:[two:value2, one:value1]]]

The only drawback is that it expects java.util.Properties instance, so you need to create one from the map.

这篇关于Groovy地图点键嵌入地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆