user3055964
user3055964

Reputation: 151

Convert WebService Response into Json Arrary and Jsobobject using Groovy

I am testing RESTful webservice using SoapUI. We use Groovy for that. I am using jsonslurper to parse the response as Object type.

Our reponse is similar to this:

{
    "language":[
        {
            "result":"PASS",
            "name":"ENGLISH",
            "fromAndToDate":null
        },
        {
            "result":"FAIL",
            "name":"MATHS",
            "fromAndToDate": {
                "from":"02/09/2016",
                "end":"02/09/2016"
            }
        },
        {
            "result":"PASS",
            "name":"PHYSICS",
            "fromAndToDate":null
        }
    ]
}

After this, I stuck up on how to.

  1. Get Array (because this is array (starts with -language)
  2. How to get value from this each array cell by passing the key (I should get the value of result key, if name='MATHS' only.)

I could do it using Java, but as just now learning Groovy I could not understand this. We have different keys with same names.

Upvotes: 0

Views: 624

Answers (1)

tim_yates
tim_yates

Reputation: 171184

You can just parse it in to a map, then use standard groovy functions:

def response = '''{
    "language":[
        {"result":"PASS","name":"ENGLISH","fromAndToDate":null},
        {"result":"FAIL","name":"MATHS","fromAndToDate":{"from":"02/09/2016","end":"02/09/2016"}},
        {"result":"PASS","name":"PHYSICS","fromAndToDate":null}
    ]
}'''

import groovy.json.*

// Parse the Json string    
def parsed = new JsonSlurper().parseText(response)

// Get the value of "languages" (the list of results)
def listOfCourses = parsed.language

// For this list of results, find the one where name equals 'MATHS'
def maths = listOfCourses.find { it.name == 'MATHS' }

Upvotes: 2

Related Questions