英文:
Groovy JsonBuilder add array element in 'for' loop
问题
我想将数组元素添加到我的 JSON 中的 'for()' 循环中。
def builder = new JsonBuilder()
def json = builder.si {
content 'test'
}
json.si.put('myList',[])
for (t=0; t < 2; t++) {
json.si.myList.add({
sval t.asString()
ival t
})
}
预期结果是
{
"si": {
"content": "test",
"myList": [
{
"sval": "0",
"ival": 0
},
{
"sval": "1",
"ival": 1
}
]
}
}
但是生成的 JSON 是
{
"si": {
"content": "test",
"myList": [
{
"sval": "2",
"ival": 2
},
{
"sval": "2",
"ival": 2
}
]
}
}
正如你所看到的,我无法将 'for' 循环变量 't' 的当前值放入 JSON 数组条目中。它总是在退出 'for' 循环后使用 't' 的值。为什么?
如果你想将循环变量 't' 的当前值添加到 JSON 数组中,你需要在每次迭代时创建一个新的 JSON 对象,并将 't' 的值添加到其中,然后再将该对象添加到数组。否则,所有对象都引用相同的 't' 的值,导致结果如你所看到的。
英文:
I want to add array elements to my JSON in a 'for()' loop
def builder = new JsonBuilder()
def json = builder.si {
content 'test'
}
json.si.put('myList',[])
for (t=0; t < 2; t++) {
json.si.myList.add({
sval t.asString()
ival t
})
}
the expected result is
{
"si": {
"content": "test",
"myList": [
{
"sval": "0",
"ival": 0
},
{
"sval": "1",
"ival": 1
}
]
}
}
but the resulting JSON is
{
"si": {
"content": "test",
"myList": [
{
"sval": "2",
"ival": 2
},
{
"sval": "2",
"ival": 2
}
]
}
}
as you can see I'm not able to put the current value of the 'for'-variabel 't' into the JSON array-entry. It always uses the value of 't' after leaving the for-loop
why?
答案1
得分: 0
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
def json = builder.si {
content 'test'
}
json.si.put('myList', [])
for (t = 0; t < 2; t++) {
json.si.myList.add([sval: t.toString(), ival: t])
}
println "JSON: ${builder.toPrettyString()}"
英文:
You may do it like that:
import groovy.json.JsonBuilder
def builder = new JsonBuilder()
def json = builder.si {
content 'test'
}
json.si.put('myList', [])
for (t = 0; t < 2; t++) {
json.si.myList.add([sval: t.toString(), ival: t])
}
println "JSON: ${builder.toPrettyString()}"
The problem in your implementation is that you don't assign value directly, but rather you declare the closure that is executed "on demand", when you already left the loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论