(这是对此处提出的问题的后续问题)
我正在使用 Groovy 的 JsonBuilder 动态生成以下 JSON:
{
"type": {
"__type": "urn",
"value": "myCustomValue1"
},
"urn": {
"__type": "urn",
"value": "myCustomValue2"
},
"date": {
"epoch": 1265662800000,
"str": "2010-02-08T21:00:00Z"
},
"metadata": [{
"ratings": [{
"rating": "NR",
"scheme": "eirin",
"_type": {
"__type": "urn",
"value": "myCustomValue3"
}
}],
"creators": [Jim, Bob, Joe]
}]
}
使用此代码:
def addUrn(parent, type, urnVal) {
parent."$type" {
__type "urn"
"value" urnVal
}
}
String getEpisode(String myCustomVal1, String myCustomVal2, String myCustomVal3) {
def builder = new groovy.json.JsonBuilder()
builder {
addUrn(delegate, "type", myCustomVal1)
addUrn(delegate, "urn", "some:urn:$myCustomVal2")
"date" {
epoch 1265662800000
str "2010-02-08T21:00:00Z"
}
"metadata" ({
ratings ({
rating "G"
scheme "eirin"
addUrn(delegate, "_type", "$myCustomVal3")
})
creators "Jim", "Bob", "Joe"
})
}
return root.toString();
}
由于StackOverflowError
第三次调用addUrn
(在嵌套ratings
元素下。如果我将该行注释掉,它会完美运行(除了我缺少必要的信息块)。
- 为什么会这样?
- 如何将委托设置为直接父级,例如
ratings
?
我试过使用 metaClass 无济于事。