如何在SoapUI中使用groovy脚本获取数组编号?

时间:2016-06-23 14:59:18

标签: json groovy soapui

我希望在Json中使用Groovy脚本来声明SoapUI响应中的属性值。我知道名字的值,但我需要知道id在哪个位置。

json响应示例:

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

让我们说我知道有一个名字Ray,我想要的位置和id(名字[1] .id)

1 个答案:

答案 0 :(得分: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