简体   繁体   中英

Need help on Groovy Script

I am trying to remove double quotes from the Value of 'version' but, not able to do that with the following groovy codes. Please help me resolving this.

  • Source JSON:

    {"version":"1", "code":'', "eccQuoteExternalQuoteId":'100000136', "reasonForRejection":'', "rejectionCode":'', "state":{"code":'SOX_APP',"integrationKey":'Approve'}, "integrationKey":''}

Groovy Script:

def Message processData(Message message) {

//Body 
def body = message.getBody(String.class);

def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)

list.each{
    it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));        
    }
def jsonOP = JsonOutput.toJson(list)
 message.setBody(jsonOP)
 return message;

}

Replace

it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));

with

it.version=it.get("version").toString().toInteger();

see the ref toInteger .

Your json is incorrect because there are single quotes used for some values. However you could try LAX parser to ignore this issue.

def jsonSlurper = new JsonSlurper().setType(JsonParserType.LAX)

If the json from question is coming through the message body then just change

list.each{
    it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));        
    }

To

list.version = list.version as Integer

@daggett is right, you can do like he said.

It seems that the value of that object is a string, not a problem of quotes. You can check the class of any the object with:

println(it.version.getClass())

if it's a string you can change it in various ways but if its a string you could simply use the below - I'm putting it in more lines just for better visibility but the result is the same as the inline from daggett

def newInt = it.version.toInteger()
it.version = newInt

There are other ways to do the same thing if you really need to convert it.

here a guide: https://www.baeldung.com/groovy-convert-string-to-integer

Maybe changing the value from string to int in that class creating the JSON is the best way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM