I\'m trying to consume a HAL-based REST service with the RestTemplate class. The response body looks like this:
{
\"_embedded\": {
\"school:teachers\":
I tried a similar approach to what Vishnoo Rath. I am planning to build a common method to do this for all my resources.
ResponseEntity<String> response =
restTemplate.exchange("http://localhost:8081/rest/cars", HttpMethod.GET, null, String.class);
String data = response.getBody();
//log.info(data);
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode jsNode = om.readTree(data);
String test = jsNode.at("/_embedded/cars").toString();
//log.info(test);
ArrayList<Car> cars = om.readValue(test, new TypeReference<List<Car>>() {
});
for (Car theCar : cars) {
log.info(">>> " + theCar.getMake() + " " + theCar.getModel() + " " + theCar.getYear());
}
I use Bowman to consume JSON+HAL resources in JAVA. This library greatly simplifies the consumption of resources comparing to RestTemplate as shown in this article.
I too faced a similar problem. And the way I chose to work around it is :
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:8080/payment/search/findByApprovalDate?approvalDate=2017-11-06", HttpMethod.GET,
null, String.class);
String data = response.getBody();
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode jsNode = om.readTree(data);
String test = jsNode.at("/_embedded/payment").toString();
payments = om.readValue(test, new TypeReference<List<RHPayment>>() {
});
Definitely, you should go with Traverson
Traverson client = new Traverson(new URI("http://localhost:8080/api/"),
MediaTypes.HAL_JSON);
Resources<Resource<Teacher>> teachers = client
.follow("school:teachers")
.toObject(new ResourcesType<Resource<Teacher>>(){});
https://docs.spring.io/spring-hateoas/docs/current/reference/html/#client.traverson