【问题标题】:Extract multiple JsonPath values from returned Response using Rest Assured使用 Rest Assured 从返回的响应中提取多个 JsonPath 值
【发布时间】:2020-10-28 15:44:14
【问题描述】:

我需要从 Rest Assured 建模请求返回的 JSON 响应数据中获取两个值:

    public void getCustomerStatuses() {

        Response response =

        given().header("X-AC-User-ID","test-user").
                spec(customerApiSpec).
        when().
                get("/api/v6/status/" + ref + "/").
        then().
                assertThat().statusCode(200).extract().response();

        custStatusId = response.path("$.cust[?(@.name=='STATUS_ID')].id");
        custRenewalId = response.path("$.cust[?(@.name=='RENEWAL_ID')].id");

        System.out.println(custStatusId);
        System.out.println(custRenewalId);

    }

这会抛出和java.lang.IllegalArgumentException: Invalid JSON expression:Script1.groovy: 1: Unexpected input: '$.cust[?' @ line 1, column 36. $.cust[?(@.name=='STATUS_ID')].id

获得这些的正确、最佳方式是什么?我知道我可以将 extract().response().jsonPath(); 链接到请求中,但不确定如何获得 >1 值

【问题讨论】:

    标签: json rest-assured jsonpath


    【解决方案1】:

    是的,您可以使用JsonPath

        Response response =
    
        given().header("X-AC-User-ID","test-user").
                spec(customerApiSpec).
        when().
                get("/api/v6/status/" + ref + "/").
        then().
                assertThat().statusCode(200).extract().response();
    
        JsonPath jsonPath = response.jsonPath();
    

    如果接收到的json体是这样的;

    {
      "value1":{
        "id": 1,
        "abc": {
            "v1": "o1",
            "v2": "o2"
        }
      },
      "value2":{
        "id": 2,
        "title": "test2"
      }  
    }
    

    然后使用get(String path)方法;

        String v1 = jsonPath.get("value1.abc.v1"); // o1
        String title = jsonPath.get("value2.title"); //  test2
    

    必需的导入;

    io.restassured.path.json.JsonPath;
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2020-11-23
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多