RestAssured ResponseBodyExtractionOptions:如何从 json 中过滤 json 个对象

RestAssured ResponseBodyExtractionOptions: How to filter json objects from json

我有一个端点响应

{
  "fruits" : {
    "apple" : "green",
    "banana" : 99,
    "oranges" : "floridaBreed",
    "lemons" : "sicilian",
    "grapes" : "red",
    "cherries" : 12,
    "guava" : "sour",
    "tomato" : 13,
    "melons" : "yellow",
    "pomegranate" : 37,
  },
  "isRaw" : null,
  "foodtype" : {
    "typeOne" : "non-veg",
    "typeTwo" : "veg"
  },
  "isCooked" : [ ],
  "isReady" : [ ],
  "isExpired" : [ ],
  "isHealthy" : null,
  "serialnumber" : 5555,
  "isAvailable" : "Yes",
  "dietValue" : {
      "nutrition" : [ {
          "vitamin" : "yes",
          "vitaminValue" : 3
      }, {
          "calcium" : "no",
          "calciumValue" : 0
      } ]
  },
  "isEdible" : null
}

我有一些代码可以获取此信息,但我无法获取嵌套值对象。例如,我可以获得 'isAvailable' 的值,即 ='yes' 但是如果我想获得 'grapes' 或 'calcium' 的值,则它不起作用。有什么想法吗?

public String sendGetMessageValue(String messageId) {
    Map<String, String> response = doInternalModuleApiGet(messageId, 200);

    return response.get("fruits.grapes");
}

public Map<String, String> doInternalModuleApiGet(
        String messageId,
        int expectedStatus) {
    String url = getInternalUrl() + "/" + messageId;
    return sendHttpGetRequestAndGetResponse(url, expectedStatus).as(Map.class);
}


private ResponseBodyExtractionOptions sendHttpGetRequestAndGetResponse(String url, int expectedStatus) {
return given()
        .header("Authorization", "basic " + B64Code.encode("dummyuser:dummypass"))
        .get(url)
        .then()
        .log().ifError().and()
        .assertThat().statusCode(equalTo(expectedStatus)).and().extract().body();
}

public String getInternalUrl() {
    return ("http://127.0.0.1:8080/api");
}

org.json 库易于使用。示例代码如下:

JSONObject completeJSON= new JSONObject(" ..YOUR JSON String Goes Here.. ");
String grapes= completeJSON.getJSONObject("fruits").getString("grapes");//Level2
String available= completeJSON.getString("isAvailable"); //Level1

您可以通过如下修改代码来获取此详细信息:

public String sendGetMessageValue(String messageId) {
    Map<String, String> response = doInternalModuleApiGet(messageId, 200);
     String fruits = response.get("fruits.grapes");
 JSONObject fruitsJSON= new JSONObject(fruits );
fruitsJSON.getString("grapes");
    return response.get("fruits.grapes");
}

您可以从以下位置找到更多示例:Parse JSON in Java

Downloadable