【问题标题】:How to create dynamic length Json array in Groovy如何在 Groovy 中创建动态长度的 Json 数组
【发布时间】:2021-07-05 06:19:13
【问题描述】:

我在 Soap UI 中使用 Groovy。我需要创建动态 JSON 大批。假设我的计数为 12,那么我需要创建 一个 JSON 数组为 {["ID": 1234,"Desc":"Apple"]} 我必须重复 IDDesc 使用不同的值在其中创建 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()

虽然我有 JSON 中的两个数组都只打印最后一个值 希望所有的值都应该以 JSON 格式作为 JSON 对象详细介绍 数组

【问题讨论】:

  • 请添加您尝试过的代码以及失败的原因(例如错误、堆栈跟踪、日志等),以便我们对其进行改进。
  • 添加了代码。请验证并帮助

标签: java groovy soapui


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    ​这对您有帮助吗:

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

    【讨论】:

    • ID 和 Desc 值将来自其他数组,并且应该在 Json 中。代码添加在主问题中
    猜你喜欢
    • 2011-10-07
    • 2019-08-10
    • 2014-04-19
    • 2019-04-19
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2020-12-05
    • 2023-02-09
    相关资源
    最近更新 更多