如何使用任意Map(动态对象)创建DSL Groovy配置文件 [英] How to create a DSL Groovy config file using an arbitrary Map (dynamic object)
本文介绍了如何使用任意Map(动态对象)创建DSL Groovy配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
> def config = [
'test':'lalala',
'nestedObject':[
foo1:'foo1 val',
foo2:'foo2 val',
nested2:[
anInt:5,
anArray:['a','b','c '],
anIntArray:[1,2,3]
]
]
]
类似于:
test ='lalala'
nestedObject {
foo1 ='foo1 val'
foo2 ='foo2 val'
nested2 {
anInt = 5
anArray = ['a','b','c' ]
anIntArray = [1,2,3]
}
}
更新:
创建配置对象
解决方案
如果您事先知道嵌套的Map结构,那么您的解决方案将起作用。如果您需要在未知的任意嵌套Map结构上执行此操作,请尝试如下所示:
import groovy.util.ConfigObject
def mapToConfig
mapToConfig = {地图 - >
map.collectEntries {k,v - >
v instanceof Map? [(k):mapToConfig(v)]:[(k):v]
}作为ConfigObject
}
给出你的输入和上面的闭包定义,下面的打印语句:
println mapToConfig config).prettyPrint()
产生此输出:
test ='lalala'
nestedObject {
foo1 ='foo1 val'
foo2 ='foo2 val'
nested2 {
anInt = 5
anArray = ['a','b','c']
anIntArray = [1,2,3]
}
}
How do I convert an arbitrary Groovy map / list to the config style DSL syntax that Groovy provides?
Example:
def config = [
'test': 'lalala',
'nestedObject': [
foo1: 'foo1 val',
foo2: 'foo2 val',
nested2: [
anInt: 5,
anArray: ['a', 'b', 'c'],
anIntArray: [1, 2, 3]
]
]
]
To something like:
test = 'lalala'
nestedObject {
foo1 = 'foo1 val'
foo2 = 'foo2 val'
nested2 {
anInt = 5
anArray = ['a', 'b', 'c']
anIntArray = [1, 2, 3]
}
}
UPDATE:
- Re-appropriating this post to explicitly ask for a dynamic/generalized solution.
- This makes it a unique question and unlike the following which assumes a known map at its initialization state: How to create ConfigObject using only nested maps in Grails?
解决方案
If you know the nested Map structure in advance, your solution will work. If you need to do this on an unknown arbitrary nested Map structure, try something like this:
import groovy.util.ConfigObject
def mapToConfig
mapToConfig = { Map map ->
map.collectEntries { k, v ->
v instanceof Map ? [(k):mapToConfig(v)] : [(k):v]
} as ConfigObject
}
Given your input and the above closure definition, the following print statement:
println mapToConfig(config).prettyPrint()
Yields this output:
test='lalala'
nestedObject {
foo1='foo1 val'
foo2='foo2 val'
nested2 {
anInt=5
anArray=['a', 'b', 'c']
anIntArray=[1, 2, 3]
}
}
这篇关于如何使用任意Map(动态对象)创建DSL Groovy配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文