簡體   English   中英

需要幫助在 Groovy 中用常量字符串替換 JSON 字段

[英]Need help on replacing JSON field with constant String in Groovy

我想用下面的 JSON 字符串替換一個 JSON 字段 - JSONtoReplace

[{"RoleName": "Normal User","ModuleName": "Calendar Management"},
 {"RoleName": "Reporter","ModuleName": "Incident Management"},
 {"RoleName": "Viewer","ModuleName": "ESG"},
 {"RoleName": "Viewer","ModuleName": "Apps"}]

源 JSON正文 {"PersonInformation":{"EmailAddress":"fabian.koehlmann@atotech.com","Name":{"FirstName":"Fabian","LastName":"KOEHLMANN","PreferredName":"Fabian Köhlmann"},"Address":{"AddressLine1":"Berlin GmbH","AddressLine2":"Erasmusstraße 20,,,,,","PostalCode":"10553"},"employeeInformation":{"EmployeeType ":"internal","EmploymentStatus":"Active","JobRole":{"Department":"Finance - IT","IsCreateDepartment":"null","JobTitle":"Specialist IT Security & Infrastructure"," SupervisorId":"null","StartDate":"09/29/2021","EffectiveDate":"null"},"Location":"Berlin GmbH","Occupation":"null"},"IsUser": "true","UserInformation":{"UserId":"7fa1785f-f4f3-42b5-96bd-33f195521635","Status":"active","Locations":{"Scope":"TRN-LOC","Roles ":"JSONtoReplace"}},"RecordUid":"2022/05/27","Id":"A0201412"}}

Groovy 腳本

def Message processData(Message message) {
   def body = message.getBody(java.lang.String) as String;
   def jsonSlurper = new JsonSlurper()      
   def SourceBody = jsonSlurper.parseText(body)
   def ReplaceData = jsonSlurper.parseText('[{"RoleName": "Normal User","ModuleName": 
          "Calendar Management"},{"RoleName": "Reporter","ModuleName": "Incident Management"}, 
              {"RoleName": "Viewer","ModuleName": "ESG"},{"RoleName": "Viewer","ModuleName": 
              "Apps"}]')
   body = body.replaceAll('JSONtoReplace','ReplaceData');
   message.setBody(body);
   return message;
}

我想替換一個 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"
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM