[英]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");
}
您可能會發現以下示例: Java中的JSON解析
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.