开发者

Groovy ConfigSlurper Configure Arrays

I am trying to create a config that would look something like this:

nods = [
    nod {
        test = 1
    },
    nod {
        test = 2
    }
]

and then use configSlurper to read it but the "node" objects appe开发者_运维技巧ar to be null after the read.

Here is my code:

final ConfigObject data = new ConfigSlurper().parse(new File("config.dat").toURI().toURL())
println  data.nods

and the output:

[null, null]

What am I doing wrong?

Thanks!


It think I resolved it this way:

config {
   nods = [
      ['name':'nod1', 'test':true],
      ['name':'nod2', 'test':flase]
   ]
}

And then using it like:

config = new ConfigSlurper().parse(new File("config.groovy").text)
for( i in 0..config.config.nods.size()-1)
    println config.config.nods[i].test

Hope this helps someone else!!


You have to be careful when using ConfigSlurper when doing this sort of thing.
For example your solution will actually produce the following output:

true
[:]

If you look carefully you will notice that there is a typo on the second array value flase instead of false

The following:

def configObj = new ConfigSlurper().parse("config { nods=[[test:true],[test:false]] }")
configObj.config.nods.each { println it.test }

should produce the correct result:

true
false


I tried to parse with ConfigSlurper something like this:

config {sha=[{from = 123;to = 234},{from = 234;to = 567}]}

The array "sha" was far from what expected. To get "sha" as an array of ConfigObjects I used a helper:

class ClosureScript extends Script {
    Closure closure

    def run() {
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure.delegate = this
        closure.call()
    }
}
def item(closure) {
    def eng = new ConfigSlurper()
    def script = new ClosureScript(closure: closure)
    eng.parse(script)
}

this way I get an array of ConfigObjects:

void testSha() {
    def config = {sha=[item {from = 123;to = 234}, item {from = 234;to = 567}]}
    def xx = item(config)
    assertEquals(123, xx.sha[0].from)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜