2016-08-22 87 views
0

我想將我的json響應值添加到數組中。我的Groovy腳本,Groovy:爲什麼節點返回null

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 
} 

陣列正在恢復, 信息:數組:[NULL,NULL,NULL]

+1

你在你的Json空間?即:'「Profile」'< - 在末尾 –

+0

是:(手動刪除空格後,我得到了這個錯誤錯誤:java.lang.IndexOutOfBoundsException:Index:600,Size:0 – Gkm

回答

3

取而代之的是的 「創建數組,調用的addAll循環」模式,嘗試這樣的:

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

(當然,一旦你從你的JSON鍵刪除空格)

+0

非常感謝你,它的工作原理。優秀:) – Gkm

+0

爲什麼它給了我一個null鍵的錯誤@tim_yates :( – Gkm

+0

@Geeta你能舉一個例子嗎?我不確定你的意思是...可能是另一個問題嗎? –