解析返回给 Gatling 的 Json 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27514947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:41:02  来源:igfitidea点击:

Parsing a Json response returned to Gatling

jsonscalagatling

提问by user1075958

I am trying to parse a json response returned to gatling by the server.

我正在尝试解析服务器返回给 gatling 的 json 响应。

My response from server is:

我的服务器回复是:

SessionAttribute(
  Session(
    GetServices,
    3491823964710285818-0,
    Map(
      gatling.http.cache.etagStore -> Map(https://api.xyz.com/services -> ), 
      gatling.http.cache.lastModifiedStore -> Map(https://api.xyz.com/services -> ),
      myresponse -> {
        "created":"2014-12-16T22:06:59.149+0000",
        "id":"x8utwb2unq8uey23vpj64t65",
        "name":"myservice",
        "updated":"2014-12-16T22:06:59.149+0000",
        "version":null
      }),
    1418767654142,622,
    OK,List(),<function1>),id)

I am doing this in my script:

我在我的脚本中这样做:

val scn = scenario("GetServices")
          .exec(http("Get all Services")
          .post("/services")
          .body(StringBody("""{ "name": "myservice" }""")).asJSON
          .headers(sentHeaders)
          .check(jsonPath("$")
          .saveAs("myresponse"))
).exec(session => {
  println(session.get("id"))
  session
})

It is still printing the whole response. How can I just retrieve the id which is "x8utwb2unq8uey23vpj64t65"?

它仍在打印整个响应。我怎样才能检索 id 是"x8utwb2unq8uey23vpj64t65"

回答by millhouse

It might be easiest to use a little bit more jsonPathto pull out the idyou need, storing thatin its own variable for later use. Remember that jsonPathis still a CheckBuilder, so you can't just access the result directly - it might have failed to match.

这可能是最容易使用的一点点jsonPath拔出id你的需要,存储的是在自己的供以后使用的变量。请记住,jsonPath它仍然是一个 CheckBuilder,因此您不能直接访问结果 - 它可能无法匹配。

Converting it to an Option[String]seems like a reasonable thing to do though.

不过,将其转换为 anOption[String]似乎是一件合理的事情。

So your final few lines would become:

所以你的最后几行将变成:

    ...
    .check(
      jsonPath("$.id").saveAs("myresponseId")
    )
  )
).exec(session => {
  val maybeId = session.get("myresponseId").asOption[String]
  println(maybeId.getOrElse("COULD NOT FIND ID"))
  session
})