使用 groovy json slurper 解析 SOAP UI 中 JSON 响应的 child 个节点

Parsing child nodes of JSON response in SOAP UI using groovy json slurper

我收到了来自网络服务的 JSON 响应,如下所示。我想使用 Groovy Json slurper 解析所有 child 结果节点并断言该值是正确的。

{
   "status": "Healthy",
   "results":    [
            {
     "name": "Microservice one",
     "status": "Healthy",
     "description": "Url check MSOneURI success : status(OK)"
  },
        {
     "name": "Microservice two",
     "status": "Healthy",
     "description": "Url check MSTwoURI success : status(OK)"
 },
        {
     "name": "Microservice three",
     "status": "Healthy",
     "description": "Url check MSThreeURI success : status(OK)"
  },
        {
     "name": "Microservice four",
     "status": "Healthy",
     "description": "Url check MSFourURI success : status(OK)"
  },
        {
     "name": "Microservice five",
     "status": "Healthy",
     "description": "Url check MSFiveURI success : status(OK)"
  }
   ]
}

这就是我所做的 - 这行得通。

//imports
import groovy.json.JsonSlurper
import groovy.json.*

//grab the response
def ResponseMessage = messageExchange.response.responseContent
// trim starting and ending double quotes
def TrimResponse     =ResponseMessage.replaceAll('^\"|\"$','').replaceAll('/\/','')

//define a JsonSlurper
def jsonSlurper = new JsonSlurper().parseText(TrimResponse)
//verify the response to be validated  isn't empty
assert !(jsonSlurper.isEmpty())


//verify the Json response Shows Correct Values 
assert jsonSlurper.status == "Healthy"
def ActualMsNames = jsonSlurper.results*.name.toString()
def ActualMsStatus = jsonSlurper.results*.status.toString()
def ActualMsDescription = jsonSlurper.results*.description.toString()


def ExpectedMsNames = "[Microservice one,Microservice two,Microservice three,Microservice four,Microservice five]"
def ExpectedMsStatus = "[Healthy, Healthy, Healthy, Healthy, Healthy]"
def ExpectedMsDescription = "[Url check MSOneURI success : status(OK),Url check MSTwoURI success : status(OK),Url check MSThreeURI success : status(OK),Url check MSFourURI success : status(OK),Url check MSFiveURI success : status(OK)]"

assert ActualMsNames==ExpectedMsNames
assert ActualMsStatus==ExpectedMsStatus
assert ActualMsDescription==ExpectedMsDescription

但我想使用某种 for 循环让它更好,它一次解析每个集合并断言 "name"、"status" 和 "descriptions" 的值每个 child

一次

这可能吗?

是的,这当然是可能的。

在不了解您的实际数据的情况下,无法给出一个完美的示例,但您可以这样做:

jsonSlurper.results?.eachWithIndex { result, i ->
    assert result.name == expectedNames[i]
    assert result.status == expectedStatus[i] // or just "Healthy" if that's the only one
    assert result.description == expectedDescriptions[i]
}

其中 expectedWhatever 是预期结果字段的列表。如果您的预期结果确实像您的示例中那样基于索引,那么您甚至可以在循环内计算它们,但我猜真实数据并非如此。