Geeta Geeta - 3 months ago 10
Groovy Question

Groovy: Why the node is returning null

I wanted to add my json response values to an array. My groovy script,

import groovy.json.*
def ResponseMessage = '''{
"Unit": {
"Screen": [{
"Profile ": {
"ID ": 12,
"Rate ": 0
},
"Rate ": 600,
"Primary ": 1,
"Audio ": [{
"Id ": 1,
"Name ": null
}],
"Pre ": 5,
"Post ": 1
}]
}
} '''
def json = new JsonSlurper().parseText(ResponseMessage)

def Screen = json.Unit.Screen
log.info Screen
def array= []
Screen.each { s ->
array.addAll(s.Rate,s.Primary,s.Pre)
log.info "array : " + array
}


Array is returning,
INFO:array : [null, null, null]

Answer

Instead of the "create an array, call addAll in a loop" pattern, try this:

def array = Screen.collectMany { s ->
    [s.Rate,s.Primary,s.Pre]
}

(Of course, once you've removed the spaces from your JSON keys)