0

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

[
{
  "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,但似乎有什么问题。任何帮助,将不胜感激。

4

1 回答 1

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"]所有孩子的报告ID

如果您知道要查找的 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。

于 2019-08-16T20:49:51.240 回答