(这是对here)
提出的问题的跟进问题我正在使用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无济于事。
答案 0 :(得分:3)
这很丑陋(LOL),但会给你预期的结果:
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()
def root = 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"
this.addUrn(delegate, "_type", "$myCustomVal3")
}]),
creators ("Jim", "Bob", "Joe")
])}])
}
println builder.toPrettyString()
}
注意: -
addUrn
方法)在调用方法时,因此在评级内部调用this
时使用addUrn
。或者,您可以将“评分”发送到类似于addUrn
。getEpisode
无法访问脚本所拥有的方法addUrn
。