groovy 将JSON对象添加到数组

xriantvc  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(244)

在第一次系统调用失败后,我得到了这个json。

{
    "header": {
        "msgCode": "400",
        "message": "Call failed!"
    },
    "body": {
        "success": false,
        "error_list": [

        ]
    }
}

在每次系统调用失败后,我都会得到receipt_code,我必须将它附加到上面的json中。

{
    "header": {
        "msgCode": "400",
        "message": "Call failed!"
    },
    "body": {
        "success": false,
        "error_list": [
            {
                "errors": [
                    {
                      "message": "Invalid receipt code!"
                    }
                ],
                "receipt_code": "A-11277809" //here is receipt_code

            }
    ]
}

}
对于所有后续调用,如果失败,则继续附加此。

{
    "header": {
        "msgCode": "400",
        "message": "Call failed!"
    },
    "body": {
        "success": false,
        "error_list": [
            {
                "errors": [
                    {
                      "message": "Invalid receipt code!"
                    }
                ],
                "receipt_code": "11111"
            },
 {
                "errors": [
                    {
                      "message": "Invalid receipt code!"
                    }
                ],
                "receipt_code": "1222"
            }
        ]
    }
}

Groovy如何做到这一点,有帮助吗?这是我代码

if(success!="true")
{
def receipt_code=receiptList[receiptFlag].receipt_code;
def error_list = []
def error ={
            "errors": [
                {
                  "message": "Invalid receipt code!"
                }
            ],
            "receipt_code": receipt_code //here is receipt_code

        }

error_list.push(error)
error_list = JSON.stringify(error_list)

msg.put("error_list",error_list);
}

我无法使用上述代码添加

8hhllhi2

8hhllhi21#

使用JsonSlurper

import groovy.json.*

String text = """
{
    "header": {
        "msgCode": "400",
        "message": "Call failed!"
    },
    "body": {
        "success": false,
        "error_list": [

        ]
    }
}
"""

def json = new JsonSlurper().parseText(text)

errors = [
    ['errors': [['message': 'hi']], 'code': 100],
    ['errors': [['message': 'hello']], 'code': 200]
]

for (err in errors)
    json.body.error_list << err

println JsonOutput.toJson(json)

输出

{
    "header": {
        "msgCode": "400",
        "message": "Call failed!"
    },
    "body": {
        "success": false,
        "error_list": [
            {
                "errors": [
                    {
                        "message": "hi"
                    }
                ],
                "code": 100
            },
            {
                "errors": [
                    {
                        "message": "hello"
                    }
                ],
                "code": 200
            }
        ]
    }
}

相关问题