java—如何在groovy中创建动态长度json数组

9w11ddsr  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(331)

我在soapui中使用groovy。我需要创建动态json数组。假设我得到的计数是12,那么我需要创建一个json数组作为 {["ID": 1234,"Desc":"Apple"]} 我必须重复一遍 IDDesc 使用不同的值在单个json中创建12个数组对象。

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()

虽然print-only最后一个值来自json中的两个数组,但我希望所有值都应该作为json对象来自json中的细节数组

ffdz8vbo

ffdz8vbo1#

您可以转置这两个数组,然后收集结果对。例如

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]]
pprl5pva

pprl5pva2#

​这是否有助于您:

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()​

相关问题