13

我有一段代码需要遍历从 REST 服务的响应中获得的 JSON 数组。(这里有完整的要点。)

.exec(http("Request_1")
  .post("/endPoint")
  .headers(headers_1)
  .body(StringBody("""REQUEST_BODY""")).asJSON
  .check(jsonPath("$.result").is("SUCCESS"))
  .check(jsonPath("$.data[*]").findAll.saveAs("pList")))
.exec(session => {
  println(session)
  session
})
.foreach("${pList}", "player"){
 exec(session => {
    val playerId = JsonPath.query("$.playerId", "${player}")
    session.set("playerId", playerId)
  })
 .exec(http("Request_1")
    .post("/endPoint")
    .headers(headers_1)
    .body(StringBody("""{"playerId":"${playerId}"}""")).asJSON
    .check(jsonPath("$.result").is("SUCCESS")))

}

第一个请求的响应格式是

{
  "result": "SUCCESS",
  "data": [
    {
      "playerId": 2
    },
    {
      "playerId": 3
    },
    {
      "playerId": 4
    }
  ]
}

playerId在会话中显示为

pList -> Vector({playerId=2, score=200}, {playerId=3, score=200}

我在第二个请求中看到正文是

{"playerId":"Right(empty iterator)}

预期:3 个请求,正文为

 {"playerId":1}
 {"playerId":2}
 {"playerId":3}

如果我只保存 playerIds,我可以成功循环结果数组:

.check(jsonPath("$.data[*].playerId").findAll.saveAs("pList")))
4

1 回答 1

17

我设法将您要查找的请求发送出去(尽管仍然收到 404,但这可能是服务器端的,或者您的 gist 发送的请求可能缺少某些内容)。诀窍是完全放弃 JsonPath:

.exec(http("Request_10")
  .get("gatling1")
  .headers(headers_10)
  .check(jsonPath("$.result").is("SUCCESS"),
  jsonPath("$.data[*]").ofType[Map[String,Any]].findAll.saveAs("pList")))
.foreach("${pList}", "player") {
  exec(session => {
    val playerMap = session("player").as[Map[String,Any]]
    val playerId = playerMap("playerId")
    session.set("playerId", playerId)
  })

在这里,jsonPathcheck 可以自动将你的 JSON 对象存储为地图,然后你可以通过 key 访问玩家 ID。值类型不必是Any,您可以使用IntorLong如果您的所有值都是数字。如果您想了解更多关于哪里出了问题的信息,请继续JsonPath阅读。


您的第一个问题是,JsonPath.query()它不仅返回您正在寻找的值。从JsonPath 自述文件中:

JsonPath.query("$.a", jsonSample) 为您提供 Right(非空迭代器)。这将允许您遍历查询的所有可能解决方案。

现在,当它说 时Right(non-empty iterator),我认为这意味着迭代器不为空。但是,如果您尝试这样做:

val playerId = JsonPath.query("$.playerId", session("player").as[String]).right.get
println(playerId)

...它打印“空迭代器”。我不确定是否存在问题JsonPathjsonPath检查或介于两者之间的用法,但没有足够的文档让我想深入研究它。

于 2014-08-19T13:15:02.420 回答