2016-06-23 94 views
1

我想通過使用SoapUI中的Groovy腳本來聲明Json響應中的屬性值。我知道名字的價值,但我需要知道id在哪個位置。如何在SoapUI中使用groovy腳本獲取數組編號?

JSON響應例如:

{ 
    "names":[ 
     { 
     "id":1, 
     "name":"Ted" 
     }, 
     { 
     "id":2, 
     "name":"Ray" 
     }, 
     { 
     "id":3, 
     "name":"Kev" 
     } 
    ] 
} 

比方說,我知道,有一個名字雷,我想要的位置和標識(名稱[1] .ID)

+0

如果名稱是「Ray」,您是否想要查找'id'值? – Rao

+0

別擔心,我的回答添加了,請檢查。 – Rao

回答

1

這裏是腳本找到相同的:

import groovy.json.* 
//Using the fixed json to explain how you can retrive the data 
//Of couse, you can also use dynamic value that you get 
def response = '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}''' 
//Parse the json string and get the names 
def names = new JsonSlurper().parseText(response).names 
//retrive the id value when name is Ray 
def rayId = names.find{it.name == 'Ray'}.id 
log.info "Id of Ray is : ${rayId}" 

//Another way to get both position and id 
names.eachWithIndex { element, index -> 
    if (element.name == 'Ray') { 
    log.info "Position : $index, And Id is : ${element.id}" 
    } 
} 

這裏你可以看到輸出

enter image description here

+0

@trans,你有機會試試嗎? – Rao

+0

這可能會拋出空指針異常,以防與「Ray」比較中的匹配項不匹配 –

相關問題