简体   繁体   English

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

[英]RestAssured ResponseBodyExtractionOptions: How to filter json objects from json

I have a endpoint which responds with 我有一个回应的端点

{
  "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
}

I have some code that gets this, bit I'm unable to get the nested value objects. 我有一些代码可以做到这一点,我无法获取嵌套的值对象。 For example I can get value for 'isAvailable' which is ='yes' But if i want to get value for 'grapes' or for 'calcium', then it does not work. 例如,我可以获取'isAvailable'的值,即='yes',但是如果我想获取'grapes'或'calcium'的值,则它不起作用。 Any ideas? 有任何想法吗?

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");
}

The org.json library is easy to use. org.json库易于使用。 Example code below: 下面的示例代码:

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

You can get this details by modifying code as below : 您可以通过修改以下代码来获取此详细信息:

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");
}

You may find extra examples from: Parse JSON in Java 您可能会发现以下示例: Java中的JSON解析

Downloadable 可下载的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM