2016-06-23 98 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”比较中的匹配项不匹配 –

相关问题