Groovy将json嵌套结构从数组转换为jsonObject

wgmfuz8q  于 2022-09-21  发布在  其他
关注(0)|答案(1)|浏览(179)

输入是

{
  "Id": ["A1", "A2", "A3"],
  "isAvailable": true,
  "isActive": true
}

输出应如下所示

{
  "Id": "A1",
  "isAvailable": true,
  "isActive": true
},

{
  "Id": "A2",
  "isAvailable": true,
  "isActive": true
},

{
  "Id": "A3",
  "isAvailable": true,
  "isActive": true
}

我尝试了以下代码,但遇到了问题,请帮帮我,我尝试了json Builder,但不起作用

def input = new JsonSlurper().parseText(inputfile);
    for (int i = 0; i < id.size(); i++){
     def output = {
                    id: id[i]
                    isAvailable:  input.isAvailable
                    isActive: input.isActive      
     }
}
s3fp2yjn

s3fp2yjn1#

简单的收集可以做到:

import groovy.json.*

def input = new JsonSlurper().parseText '{"Id": ["A1", "A2", "A3"],"isAvailable": true,"isActive": true }'

def result = input.Id.collect{ input + [ Id:it ] }

assert JsonOutput.prettyPrint( JsonOutput.toJson( result ) ) == '''
[
    {
        "Id": "A1",
        "isAvailable": true,
        "isActive": true
    },
    {
        "Id": "A2",
        "isAvailable": true,
        "isActive": true
    },
    {
        "Id": "A3",
        "isAvailable": true,
        "isActive": true
    }
]'''

相关问题