Getting JSON data in Groovy

Viewed 37

I need to get some datas from JSON, I could manage to transform it into String. For example, I need to get the amount value if team role id is 4.( The last scope in the JSON.) When I run the code below, the "result" output is

{id=1, effectiveDate=2003-01-01, currencyCode=USD, rates=[{id=1, rateTable={id=1, effectiveDate=2003-01-01, currencyCode=USD, name=Tempo Default Price Table, defaultTable=false}, amount=0.0, link={type=DEFAULT_RATE}}], name=Tempo Default Price Table, defaultTable=true}

How can I get the whole data? Thanks.

 
http.request(Method.GET) {
    response.success = { resp, json ->
       
        arrayDen = JsonOutput.toJson(json).substring(1, JsonOutput.toJson(json).length()-1)
    }
}
        def slurper = new groovy.json.JsonSlurper()
        def result = slurper.parseText(arrayDen)
        log.warn(result) 

[
    {
        "id": 1,
        "rateTable": {
            "id": 1,
            "effectiveDate": "2003-01-01",
            "currencyCode": "USD",
            "name": "Tempo Default Price Table",
            "defaultTable": false
        },
        "amount": 0.0,
        "link": {
            "type": "DEFAULT_RATE"
        }
    },
    {
        "id": 2,
        "rateTable": {
            "id": 3,
            "effectiveDate": "2022-03-21",
            "currencyCode": "USD",
            "name": "Rate",
            "defaultTable": false
        },
        "amount": 0.0,
        "link": {
            "type": "DEFAULT_RATE"
        }
    },
    {
        "id": 3,
        "rateTable": {
            "id": 3,
            "effectiveDate": "2022-03-21",
            "currencyCode": "USD",
            "name": "Rate",
            "defaultTable": false
        },
        "amount": 200.0,
        "link": {
            "type": "TEAM_ROLE",
            "id": 8
        }
    },
    {
        "id": 4,
        "rateTable": {
            "id": 3,
            "effectiveDate": "2022-03-21",
            "currencyCode": "USD",
            "name": "Rate",
            "defaultTable": false
        },
        "amount": 500.0,
        "link": {
            "type": "TEAM_ROLE",
            "id": 5
        }
    },
    {
        "id": 5,
        "rateTable": {
            "id": 3,
            "effectiveDate": "2022-03-21",
            "currencyCode": "USD",
            "name": "Rate",
            "defaultTable": false
        },
        "amount": 1000.0,
        "link": {
            "type": "TEAM_ROLE",
            "id": 4
        }
    }
]

`

1 Answers

Hmmm. The following worked fine for me:

def arrayDen = '<YOUR_URL_GOES_HERE>'.toURL().text

def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(arrayDen)

def desiredData = result.find { it.id == 4 }
println desiredData.amount

You might give it a try.

Related