需要有关在Groovy中将JSON字段替换为常量字符串的帮助

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

{"header":{"type":"auto_translation","ret_code":"error","time_cost":1057.0,"request_id":"2360e0de599911ed8b7ea7989c294558"},"message":"Translation error (20001), please retry later. Detail: RuntimeException - The length of source sentence is too long!!! - {\n "header": {\n "time_cost": 0.000283,\n "type": "auto_translation",\n "ret_code": "The length of source sentence is too long!!!"\n }\n}"}

a0x5cqrl

a0x5cqrl1#

我想替换JSON字段
您可以执行以下操作:

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

// ...

// This hardcoded String represents "body" from the code in the question
String jsonString = '''
[{"RoleName": "Normal User","ModuleName": "Calendar Management"},
{"RoleName": "Reporter","ModuleName": "Incident Management"}]
'''
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)

println 'Before Update...'
println new JsonBuilder(json).toPrettyString()

json[0].'RoleName' = 'Updated'

println 'After Update...'
println new JsonBuilder(json).toPrettyString()

输出:

Before Update...
[
    {
        "RoleName": "Normal User",
        "ModuleName": "Calendar Management"
    },
    {
        "RoleName": "Reporter",
        "ModuleName": "Incident Management"
    }
]
After Update...
[
    {
        "RoleName": "Updated",
        "ModuleName": "Calendar Management"
    },
    {
        "RoleName": "Reporter",
        "ModuleName": "Incident Management"
    }
]

相关问题