使用 Groovy 的 ConfigSlurper 读取带有嵌套闭包的配置文件

发布于 2024-12-20 02:21:49 字数 1074 浏览 2 评论 0原文

我想用 Groovy 的 ConfigSlurper。解析结果将存储在类似于数据结构的对象层次结构中。该数据结构的唯一特别之处在于,一些闭包名称在一个闭包内重复出现,例如 applegreen。我看起来 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兲鉂ぱ嘚淚 2024-12-27 02:21:49

我能够使用 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 in Binding object lets you retrieve the values. For the repetitive closures I had to change the closure's resolveStrategy to Closure.DELEGATE_FIRST.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文