Lucas Crostarosa Lucas Crostarosa - 3 months ago 8
Groovy Question

Groovy Calling/Looping through JSON Objects

I am using groovy's

RESTClient
to make an
HTTP GET
Request and have a
JSON
response object that looks like this

{
"page": 1,
"pages": 1,
"count": 4,
"items": [{
"id": 291938,
"type": email,
"folder": "1234",
"isDraft": "false",
"number": 349,
"owner": {
"id": 1234,
"firstName": "Jack",
"lastName": "Sprout",
"email": "jack.sprout@gmail.com",
"phone": null,
"type": "user"
},
"mailbox": {
"id": 1234,
"name": "My Mailbox"
}
}]
}


I set my code like so

def Client = new RESTClient('https://api.myapi.net/v1/conversations/' )
helpscout.setHeaders([Authorization: "Basic 1234", Accept: 'application/json'])
def resp = Client.get(contentType: JSON)
def myResponseObject = resp.getData()


I need to be able to loop through multiple API calls/JSON objects, and store all of the response items into their own variables/classes, and output them as necessary.

I'm coming from a python background, and am used to being able to call a specific item by saying
responseObject['items']['id']
, but in this case I can't do that.

My question to you is, how am I able to access one of these items, and do whatever I need to do with it/store it into a variable

This is my debugger output below
enter image description here

Answer

As getData() returns a Map you can just reference the fields in the JSON like so:

...
def myResponseObject = resp.getData()
def page = myResponseObject.page
def count = myResponseObject.count
println page // prints 1
println count //prints 4

// Print all items
myResponseObject.items.each {
    println "item: $it"
}

// The python example responseObject['items']['id'] in groovy is
responseObject.items[0].id

// To get the first items createdAt field (according to the image)
println responseObject.items[0].createdAt
Comments