jsongroovysoapuijsonslurper

How to use JsonSlurper?


I have written a test case in SOAP UI which creates a user and returns the Id. This is the JsonResponse. Through a Groovy script, I need to extract the id

{
    "schemas":["urn:hid:scim:api:ma:1.0:UserInvitation"],
    "urn:hid:scim:api:ma:1.0:UserInvitation":
        [
            {
                "meta":{ 
                    "resourceType":"UserInvitation",                                                   
                    "lastModified":"2015-12-22T07:45:30Z",
                    "location":"https://test-ma.api.assaabloy.com/credential-management/customer/663/invitation/2643209"
                },
                "invitationCode":"FBXO-SRWS-LKFI-ZKZI",
                "status":"PENDING",
                "createdDate":"2015-12-22T02:45:30Z",
                "expirationDate":"2015-12-22T02:45:30Z",
                "id":2643209
             }
         ]
}

I'm very new to Groovy. Please help me with this.


Solution

  • It will be:

    import groovy.json.JsonSlurper
    
    def json = """
    {
        "schemas":["urn:hid:scim:api:ma:1.0:UserInvitation"],
        "urn:hid:scim:api:ma:1.0:UserInvitation":
            [
                {
                    "meta":{ 
                        "resourceType":"UserInvitation",                                                   
                        "lastModified":"2015-12-22T07:45:30Z",
                        "location":"https://test-ma.api.assaabloy.com/credential-management/customer/663/invitation/2643209"
                    },
                    "invitationCode":"FBXO-SRWS-LKFI-ZKZI",
                    "status":"PENDING",
                    "createdDate":"2015-12-22T02:45:30Z",
                    "expirationDate":"2015-12-22T02:45:30Z",
                    "id":2643209
                 }
             ]
    }"""
    def slurped = new JsonSlurper().parseText(json)
    assert 2643209 == slurped."urn:hid:scim:api:ma:1.0:UserInvitation"[0].id
    

    new JsonSlurper().parseText(json) statement will return an instance of the map interface. So using this map you can get the list with this statement: slurped."urn:hid:scim:api:ma:1.0:UserInvitation", then the first element using getAt operator ([0]) and finally with id you get the desired value.