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. 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. 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