简体   繁体   中英

Access values in JSON based on a condition using Groovy

I am trying to extract two sets of information from the httpResponse (in the form of JSON)-
1. Location
2. city where fruit = Apple and luckyNumber = 10.

{
    "userInformation": {
        "Name": "John",
        "Location": "India"
    },
    "details": [
        {
            "fruit": "Apple",
            "color": "Red",
            "city": "New Delhi",
            "luckyNumber": 10
        },
        {
            "fruit": "Banana",
            "color": "yellow",
            "city": "Goa",
            "luckyNumber": 12
         }
         ]
         }

For extracting the Location, I tried the below code:

def slurper = new JsonSlurper().parseText(httpResponse)

userLocation = slurper.userInformation.Location

This gives me an error -

javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.LinkedHashMap) values: [[statusCode:200, reason:OK, headers:[Access-Control-Allow-Credential:true, ...], ...]] Possible solutions: parseText(java.lang.String), parse([B), parse([C), parse(java.io.File), parse(java.io.InputStream), parse(java.io.Reader) 

the error

No signature of method: groovy.json.JsonSlurper.parseText() is applicable for
       argument types: (java.util.LinkedHashMap)
Possible solutions: parseText(java.lang.String), ...

means that you try to pass Map ( httpResponse ) into JsonSlurper.parseText() when this method accepts String.

Find how to get response body as a string and then you can use JsonSlurper.parseText()

Probably you need httpResponse.getData() or just httpResponse.data to access response data payload. This data may already be in map, if response was parsed correctly based on Content-Type, in this case you do not need to use JsonSlurper. If data is a json String then use JsonSlurper.

In any case you will have something like

def cities = responseData.details.findAll{it.fruit=="Apple" && it.luckyNumber==10}

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