[英]How to create dynamic length Json array in Groovy
I am using Groovy in Soap UI.我在 Soap UI 中使用 Groovy。 I have requirement to create dynamic JSON array.
我需要创建动态 JSON 数组。 Let's say I am getting an count as 12, then I need to create a JSON Array as
{["ID": 1234,"Desc":"Apple"]}
and I have to repeat ID
and Desc
with different values to create 12 array object in single JSON.假设我的计数为 12,然后我需要创建一个 JSON 数组作为
{["ID": 1234,"Desc":"Apple"]}
并且我必须用不同的值重复ID
和Desc
以创建 12单个 JSON 中的数组对象。
def IDValue = ... // One Array where all IDs are stored
def Description = ... // Second Array where all desc are stored
JsonBuilder builder = new JsonBuilder()
for(int i=0; i<Array.length; i++) {
def currIDValue = IDValue[i]
def currDescription =Description[i]
builder{Details([i].collect{[id : currIDValue,"Desc": currDescription]})}
}
Log.info builder.toPrettyString()
While print only last value is coming of both the array in JSON I have wanted all the values should come in JSON as JSON objects in Detail array虽然仅打印最后一个值来自 JSON 中的数组,但我希望所有值都应以 JSON 形式作为 Detail 数组中的 JSON 对象出现
Does this helps you :这对您有帮助吗:
import groovy.json.*
def IDValue = [1,2,3,4]
def Description = ["decs1","decs2","decs3","decs4"]
def array=[]
for(int i=0; i<3; i++) {
array+=["Id": IDValue[i], "Desc":Description[i]]
}
JsonBuilder builder = new JsonBuilder(array)
println builder.toPrettyString()
You can transpose the two arrays and then collect over the resulting pairs.您可以转置两个数组,然后收集结果对。 Eg
例如
def ids = [1,2,3,]
def descs = ["a", "b", "c",]
[ids, descs].transpose().collect{ id, desc -> [id: id, desc: desc] }
// → [[id:1, desc:a], [id:2, desc:b], [id:3, desc:c]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.