I have a method that calls an endpoint to post a customer How can i get only the message "EMAIL ALREADY EXISTS" from the ResponseBody of Rest Template in order to show it in the FacesContext
try {
return restTemplate.exchange("http://localhost:8030/addCustomer", HttpMethod.POST, entity, String.class);
catch (HttpStatusCodeException e) {
var facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sorry", e.getResponseBodyAsString()));
return
ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
}
This is the response Body
{"httpStatusCode":400,"httpStatus":"BAD_REQUEST","reason":"BAD REQUEST","message":"EMAIL ALREADY EXISTS","timestamp":"11-04-2022 03:52:43"}
CodePudding user response:
I don't see any built-in way to access the message property. However, since the response body is in JSON, you could parse the body to a JSON object and then get the field value from that object.
CodePudding user response:
You can parse the responseBody to a JsonNode and use the function findValue to get the property you want.
JsonNode node = mapper.readValue(e.getResponseBodyAsString(), JsonNode.class);
mapper.convertValue(node.findValue("message"), String.class);
CodePudding user response:
Use this as an example:
val msg = ""
val response = restTemplate.exchange(
"http://localhost:8030/addCustomer",
HttpMethod.POST,
HttpEntity<T>(headers),
Array<Any>::class.java
)
response.body?.forEach { it ->
val data = it as LinkedHashMap<String,Any>
msg = data["message"].toString()
}
return msg
PS: I'm sorry the example is in kotlin code