Jenisha
Jenisha

Reputation: 225

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?

Upvotes: 7

Views: 40506

Answers (1)

Dmytro Buryak
Dmytro Buryak

Reputation: 368

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

Upvotes: 14

Related Questions