Groovy JsonBuilder在’for’循环中添加数组元素

huangapple go评论53阅读模式
英文:

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 &#39;test&#39;
  }
  json.si.put(&#39;myList&#39;,[])
  for (t=0; t &lt; 2; t++) {
    json.si.myList.add({
      sval t.asString()
      ival t
    })

  }

the expected result is

{
	&quot;si&quot;: {
		&quot;content&quot;: &quot;test&quot;,
		&quot;myList&quot;: [
			{
				&quot;sval&quot;: &quot;0&quot;,
				&quot;ival&quot;: 0
			},
			{
				&quot;sval&quot;: &quot;1&quot;,
				&quot;ival&quot;: 1
			}
		]
	}
}

but the resulting JSON is

{
	&quot;si&quot;: {
		&quot;content&quot;: &quot;test&quot;,
		&quot;myList&quot;: [
			{
				&quot;sval&quot;: &quot;2&quot;,
				&quot;ival&quot;: 2
			},
			{
				&quot;sval&quot;: &quot;2&quot;,
				&quot;ival&quot;: 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 &#39;test&#39;
}
json.si.put(&#39;myList&#39;, [])
for (t = 0; t &lt; 2; t++) {
    json.si.myList.add([sval: t.toString(), ival: t])
}

println &quot;JSON: ${builder.toPrettyString()}&quot;

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.

huangapple
  • 本文由 发表于 2023年5月22日 21:16:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定