Search code examples
jsondictionarygroovyhttpbuilder

httpBuilder JSON response parse includes [ ]


This may be very obvious so please be gentle.

The following code:

def http = new HTTPBuilder(uri)

http.request(POST,JSON ) { req ->
    headers.'Content-Type' = 'application/json'
    headers.'x-chkp-sid' = CHKPsid
    body = [
            "limit" : 100,
            "offset" : 0,
            "details-level" : "standard"
    ]

    response.success = { resp, json ->
       println (json)
       println "POST Success. SHOWGWS: ${resp.statusLine}"
       println json.objects.name
       println json.size()
       println json.getClass()
     assert json.objects.name == 'gw-6eee89'
    }
}

gives the following output:

[objects:[[uid:892d08fb-0dca-5146-8587-49fa07ece24c, name:gw-6eee89, type:simple-gateway, domain:[uid:41e821a0-3720-11e3-aa6e-0800200c9fde, name:SMC User, domain-type:domain]]], from:1, to:1, total:1]

POST Success. SHOWGWS: HTTP/1.1 200 OK

[gw-6eee89]

4

class groovy.json.internal.LazyMap

Caught: Assertion failed: 

   assert json.objects.name == 'gw-6eee89'
       |    |       |    |
       |    |       |    false
       |    |       [gw-6eee89]
       |    [[uid:892d08fb-0dca-5146-8587-49fa07ece24c, name:gw-6eee89, type:simple-gateway, domain:[uid:41e821a0-3720-11e3-aa6e-0800200c9fde, name:SMC User, domain-type:domain]]]
       [objects:[[uid:892d08fb-0dca-5146-8587-49fa07ece24c, name:gw-6eee89, type:simple-gateway, domain:[uid:41e821a0-3720-11e3-aa6e-0800200c9fde, name:SMC User, domain-type:domain]]], from:1, to:1, total:1]

It appears to be comparing gw-6eee89 to [gw-6eee89]

I cannot see why the square brackets are not removed when the value is called. Any help much appreciated.


Solution

  • Since objects is an instance of List and if you call list.someProperty you will get a list of someProperty values for all objects on the list:

    [[name:1],[name:2]].name == [1, 2]
    

    You need to fetch the first object. So e.g.: objects.name[0].