我通过使用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错误。
请帮忙。
答案 0 :(得分:1)
尝试使用以下行将restassured响应体转换为JSONObject格式:
JSONObject responseJSONObject = new JSONObject(response.getBody().asString);
答案 1 :(得分: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.");