如何使用REST-Assured库在groovy的闭包中使用find或findAll在匿名和嵌套数组中进行搜索?

时间:2019-06-06 11:48:53

标签: groovy rest-assured jsonpath rest-assured-jsonpath gpath

我有以下JSON响应匿名主体,我需要动态解析嵌套数组以根据条件在Groovy的闭包中使用findfindAll来检索键的值

[
{
  "children": [
    {
      "attr": {
        "reportId": "1",
        "reportShortName": "ABC",
        "description": "test,
      }
    },
   {
     "attr": {
       "reportId": "2",
       "reportShortName": "XYZ",
       "description": "test",
      }
   }
}
]

我尝试了以下方法,但没有运气从JSON响应中检索reportId键的值

package com.src.test.api;
import static io.restassured.RestAssured.given;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class GetReportId {
   public void getReportId(String reportName) throws Exception {
    String searchReports = "http://localhost:8080/reports";
    Response resp=given().request().when().get(searchReports).then().extract().response();
    JsonPath jsonPath = new JsonPath(resp.asString());

    String reportId1 =jsonPath.get("$.find{it.children.contains(restAssuredJsonRootObject.$.children.find{it.attr.reportShortName == 'ABC'})}.attr.reportId");
    String reportId2 = jsonPath.get("$.find{it.children.attr.reportShortName.contains(restAssuredJsonRootObject.$.children.find{it.attr.reportShortName.equals('XYZ')}.attr.reportShortName)}.attr.reportId");
    System.out.println("ReportId: " + reportId1);
  }
}

父匿名数组中可能有多个JSON对象,需要使用groovy闭包内的find或findAll来获取reportId

需要获取reportId,但似乎出了点问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

假设您需要所有reportIds

List<String> reportIds = jsonPath.get("children.flatten().attr.reportId");

将提供您想要的内容,即使父匿名数组具有多个条目。

我使用以下JSON测试了

[
  {
    "children": [
      {
        "attr": {
          "reportId": "1",
          "reportShortName": "ABC",
          "description": "test"
        }
      },
      {
        "attr": {
          "reportId": "2",
          "reportShortName": "XYZ",
          "description": "test"
        }
      }
    ]
  },
  {
    "children": [
      {
        "attr": {
          "reportId": "3",
          "reportShortName": "DEF",
          "description": "test"
        }
      },
      {
        "attr": {
          "reportId": "4",
          "reportShortName": "IJK",
          "description": "test"
        }
      }
    ]
  }
]

它给了我["1", "2", "3", "4"],即所有孩子的reportIds

如果您知道要查找的reportId的索引,则可以这样使用它:

String reportId = jsonPath.get("children.flatten().attr.reportId[0]");

如果您要查找特定报告的reportId,也可以这样做:

String reportId = jsonPath.get("children.flatten().attr.find{it.reportShortName == 'ABC'}.reportId")

会给您"1"

注意:您将结果分配给的变量的类型对于类型推断和强制转换很重要。例如,您不能执行以下操作:

String [] reportIds = jsonPath.get("children.flatten().attr.reportId");

int reportId = jsonPath.get("children.flatten().attr.reportId[0]");

这两种东西都会抛出ClassCastException。