Create a Collection from json response

Hi, I'm new in this forum ..

I have a process that executes a REST api call and obtains a result similar to a collection:

I would like to convert this response into a Map or into a List

How can I do that ?

Is the "forEach" operation usefull ? How do I use it ?

this is the json response:

 

{
    "myResponse": {
        "properties": {
            "property": [
                {
                    "name": "aa",
                    "value": "1"
                },
                {
                    "name": "bb",
                    "value": "2"
                },
                {
                    "name": "cc",
                    "value": "3"
                }
            ]
        }
    }
}

 

 

1 Like

Hi bluca,

in order to parse your response an iterata, you can use this groovy method:

def jsonParseExample() {
        given:
        JsonSlurper slurper = new JsonSlurper()
        def json = '''
{
    "myResponse": {
        "properties": {
            "property": [
                {
                    "name": "aa",
                    "value": "1"
                },
                {
                    "name": "bb",
                    "value": "2"
                },
                {
                    "name": "cc",
                    "value": "3"
                }
            ]
        }
    }
}'''
        when:
        def parsed = slurper.parseText(json)

        then:
        parsed.myResponse.properties.property.size() == 3
        parsed.myResponse.properties.property.each { prop ->
            System.out.println("name:${prop.name} value:${prop.value}")
        }
    }

output will produce:

name:aa value:1
name:bb value:2
name:cc value:3
2 Likes