2011-04-27 155 views
3

我想創建一個配置,將是這個樣子:Groovy的ConfigSlurper配置陣列

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

,然後用configSlurper讀它,但「節點」對象出現在讀取後爲空。

這裏是我的代碼:

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

和輸出:

[null, null] 

我在做什麼錯?

謝謝!

回答

15

它想我解決這樣說:

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

,然後用它喜歡:

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

希望這可以幫助其他人!

0

在做這類事情時,你必須小心使用ConfigSlurper。
例如您的解決方案實際上會產生以下輸出:

true 
[:] 

如果你仔細觀察,你會發現,有第二陣列值FLASE,而不是虛假的錯字

的如下:

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

應該產生正確的結果:

true 
false 
0

我試着用ConfigSlurper像這樣解析:

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

陣列「沙」是我們所期望的遠。 要獲得「沙」爲ConfigObjects數組我用了一個幫手:

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) 
} 

這樣我得到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) 
}