【问题标题】:RestAssured - JsonPath filter a matching Object's properties from an array of objects, given a filter criteriaRestAssured - JsonPath 在给定过滤条件的情况下从对象数组中过滤匹配对象的属性
【发布时间】:2017-12-08 12:21:50
【问题描述】:

我正在使用“放心”为我的微服务编写集成测试。我有一个这样的 Json 有效负载,它是从它返回的。

{
   "sessionQuestions":[
      {
         "id":1272,
         "sessionId":1146,
         "questionId":"1002",
      },
      {
         "id":1273,
         "sessionId":1146,
         "questionId":"1004",
      }
   ]
}

在给定 questionId 值的情况下,我需要找到会话问题的 id。然后我需要在我的断言中比较它们。给定 questionId 值,我很难从 sessionQuestion 中获取 id。我正在使用 JsonPath 来完成这件事。这是我的 Json 路径表达式。

new JsonPath(response).get("$.sessionQuestions[?(@.questionId=='1002')].id");

这会引发错误。

java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' @ line 1, column 45.
   nRootObject.$.sessionQuestions[?(@.quest
                                 ^

1 error

   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

我在这个在线evaluator中尝试了相同的Json路径表达式,效果很好。我正在使用json-path-2.9.0.jar

我在这里做错了什么?非常感谢任何帮助。

【问题讨论】:

    标签: java json rest-assured jsonpath rest-assured-jsonpath


    【解决方案1】:

    您使用哪个版本的 JsonPath?我用this

    适用于您的情况的代码是:

    JsonPath.parse(response).read("$.sessionQuestions[?(@.questionId=='1002')].id").toString();
    

    并尝试使用此 JSON:

    {
       "sessionQuestions":[
          {
             "id":1272,
             "sessionId":1146,
             "questionId":"1002"
          },
          {
             "id":1273,
             "sessionId":1146,
             "questionId":"1004"
          }
       ]
    }
    

    编辑:如果你使用这个依赖(json-path-2.9.0),你必须这样做:

    from(response).getList("sessionQuestions.findAll { it.questionId=='1002' }.id").toString();
    

    你必须像这样导入:

    import static com.jayway.restassured.path.json.JsonPath.from;
    

    【讨论】:

    • 不走运。用我正在使用的 Json 路径版本更新了问题。谢谢。
    • 不幸的是它没有parseread 方法。
    • 我更新了我的答案。尝试更具体地介绍您即将发布的帖子:) 也可以在这里查看github.com/rest-assured/rest-assured/wiki/Usage
    • 感谢您的解决方案。 from(response).getList("sessionQuestions.findAll { it.questionId=='1002' }.id").toString(); 在我直接使用 rest-assured 的 jsonpath 时帮助了我。 Jayway 的 jsonpath 与放心的不同,因此它导致了更多的复杂性。
    • @CMM 这是非常有帮助的回复,我使用 JsonPath 来验证响应,感谢您提到这个技巧直接与 jsonPath 一起使用,如下所示 =========== ===============>JsonPath pastPartnerUsersListResponseJson= pastPartnerUsersListResponse.getBody().jsonPath(); String pendingCcoId= pastPartnerUsersListResponseJson.getList("data.findAll{it.accessOrder==1}.ccoId").stream().collect(Collectors.toList()).get(0).toString();我在这里有一个基本问题,它是什么,你用过,它是如何使用的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2016-10-13
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多