1

我通过使用 java 的 restAssured 击中发布请求,以 json 格式从服务器获得响应。

Response response = requestSpecification.body(text).post(endpoint);

现在我想获取名为“freebies”的子 json 对象。我该如何执行此操作,因为当我在写作时:

JSONObject responseJSONObject = new JSONObject(response);

//jsonObject.getJSONObject("freebies").getString("id");

JSONArray list = jsonObject.getJSONArray("freebies");

String freebies = list.getJSONObject(0).getString("id");

    for (int i = 0; i < freebies.length(); i++) {
        String id = list.getJSONObject(i).getString("id");
        System.out.println(id.toString());
        String name = list.getJSONObject(i).getString("name");
        System.out.println(name.toString());
        String packName = list.getJSONObject(i).getString("packName");
        System.out.println(packName.toString());
        String quota = list.getJSONObject(i).getString("quota");
        System.out.println(quota.toString());

我收到 stackoverFlow 错误。

请帮忙。

4

3 回答 3

2

尝试使用下面的行将放心的响应正文转换为 JSONObject 格式:

JSONObject responseJSONObject = new JSONObject(response.getBody().asString);
于 2018-03-30T16:24:52.797 回答
0
ValidatableResponse statusResponse = givenJsonRequest().when()
    .get("/field/entity/test").then();
ArrayList<Map<String,?>> jsonAsArrayList = statusResponse.extract()
    .jsonPath().get("");
Optional<Map<String,?>> filtered = jsonAsArrayList.stream()
    .filter(m -> m.get("fieldName1").equals("Whatever1"))
    .filter(m -> m.get("jsonObject").toString().contains("Whatever2"))
    .findFirst();
Assert.assertTrue(filtered.isPresent(), "Test expected a result after filtering.");
于 2018-04-07T18:15:58.580 回答
0

在 RestAssured 4.4.0 中,以下工作:

JSONObject jsonObject = new JSONObject(response.jsonPath().getJsonObject("$"));

于 2022-01-17T05:27:21.380 回答