I have created a REST web service.
I have in the response, a nested list with 5 key-value associations in each list. I only want to check if each value has the right format (boolean, string or integer).
So this is the nested list.
{"marches": [
{
"id": 13,
"libelle": "CAS",
"libelleSite": "USA",
"siteId": 1,
"right": false,
"active": true
},
{
"id": 21,
"libelle": "MQS",
"libelleSite": "Spain",
"siteId": 1,
"right": false,
"active": true
},
{
"id": 1,
"libelle": "ASCV",
"libelleSite": "Italy",
"siteId": 1,
"right": false,
"active": true
}]
}
I use the JsonSlurper class to read the groovy response.
import groovy.json.JsonSlurper
def responseMessage = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(responseMessage)
With this following loop, I achieve in getting each block of list.
marches.each { n ->
log.info "Nested $n \n"
}
I want for instance check if the value associated to the key "id", "13" is well an integer and so on.
You're almost there. Inside of the .each
, it
represents the nested object:
json.marches.each {
assert it.id instanceof Integer // one way to do it
//another way
if( !(it.libelle instanceof String) ){
log.info "${it.id} has bad libelle"
}
//one more way
return (it.libelleSite instanceof String) &&
(it.siteId instanceof Integer) && (it.right instanceof Boolean)
}
If you don't care about the specifics and just want to make sure they're all good, you can also use .every
:
assert json.marches.every {
it.id instanceof Integer &&
it.libelle instanceof String &&
it.libelleSite instanceof String &&
it.active instanceof Boolean //...and so on
}