How to Convert Java. Lang. String to Json in Groovy

How to Convert Java. Lang. String to Json in Groovy

My java.lang.String is of form

 [[{"ABC":{"total":0,"failed":0,"skipped":0}}], [{"BCD": {"total":0,"failed":0,"skipped":0}}]]

How to convert this to json in groovy?

3

1 Answer

Parsing json from string with built-in groovy tools is done with groovy.json.JsonSlurper. You can check the documentation at here.

Here's how your example json can be accessed, just like groovy nested map:

def str = '[[{"ABC":{"total":0,"failed":0,"skipped":0}}], [{"BCD": {"total":0,"failed":0,"skipped":0}}]]'
def parser = new JsonSlurper()
def json = parser.parseText(str)
assert json[0][0].ABC.total == 0
assert json[0][0].ABC.failed == 0
assert json[0][0].ABC.skipped == 0
assert json[1][0].BCD.total == 0
assert json[1][0].BCD.failed == 0
assert json[1][0].BCD.skipped == 0
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.