使用 Groovy 的 ConfigSlurper 读取带有嵌套闭包的配置文件
我想用 Groovy 的 ConfigSlurper。解析结果将存储在类似于数据结构的对象层次结构中。该数据结构的唯一特别之处在于,一些闭包名称在一个闭包内重复出现,例如 apple
和 green
。我看起来 ConfigSlurper 正在内部使用 Map
来替换现有的值。我想知道 ConfigSlurper 是否真的能够处理这些类型的数据结构。我使用的 Groovy 版本是 1.7.10。或者,我尝试使用 GroovyShell 来执行闭包,但执行顺序存在一些问题。
String rules = """
fruits {
apples {
apple {
id = 11
colors {
green {
name = 'test1'
}
green {
name = 'test2'
}
}
}
apple {
id = 12
colors {
green {
name = 'test3'
}
green {
name = 'test4'
}
}
}
}
}
"""
ConfigSlurper configSlurper = new ConfigSlurper()
def config = configSlurper.parse(rules)
println config
I would like to parse a data structure of closures (in this case a configuration file) with Groovy's ConfigSlurper. The parsing result will be stored in an object hierarchy similar to the data structure. The only thing special about this data structure is the fact that some closure names repeat themselves within one closure e.g. apple
and green
. I looks like ConfigSlurper
is using a Map
internally that replaces already existing values. I was wondering if ConfigSlurper
is actually able to handle these kinds of data structures. The Groovy version I use is 1.7.10. Alternatively, I tried to use GroovyShell
to execute the closures but had some issues with the execution order.
String rules = """
fruits {
apples {
apple {
id = 11
colors {
green {
name = 'test1'
}
green {
name = 'test2'
}
}
}
apple {
id = 12
colors {
green {
name = 'test3'
}
green {
name = 'test4'
}
}
}
}
}
"""
ConfigSlurper configSlurper = new ConfigSlurper()
def config = configSlurper.parse(rules)
println config
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够使用
GroovyShell
解析这些规则。每个规则的关闭都需要执行。传入的Binding
对象可让您检索值。对于重复的闭包,我必须将闭包的resolveStrategy
更改为Closure.DELEGATE_FIRST
。I was able to parse these rules using
GroovyShell
. Each closure of the rules needs to executed. The passed inBinding
object lets you retrieve the values. For the repetitive closures I had to change the closure'sresolveStrategy
toClosure.DELEGATE_FIRST
.