Gkm
Gkm

Reputation: 247

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]

Upvotes: 0

Views: 211

Answers (1)

tim_yates
tim_yates

Reputation: 171054

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)

Upvotes: 3

Related Questions