Consuming REST HAL-formatted JSON with Spring RestTemplate

Spring Data Rest uses HAL as the default media presentation format so the JSON content type is application/hal+json. HAL stands for "Hypertext Application Language." This means JSON resources are embedded and are wrapped in an _embedded property.

A straight JSON output would look like this, with no "_embedded" tag or resource name, brackets front and back.

So we need a different approach on consuming REST HAL-formatted JSON when using Spring RestTemplate to retrieve the actual Post objects.

If you're having problems consuming Spring Data Rest objects, you're not alone. You'll find developers with HAL JSON consumption problems on this StackOverflow post and elsewhere. I was in the "empty Collections" group for quite some time until I discovered the solution from Biju Kunjummen written up in this Java Zone article and demonstrated in his hateos-sample project.

The RestTemplate Configuration

We'll begin with the solution which is to add a Type-Constrained Converter to our RestTemplate. We'll put its name on a separate line since it's so long.

TypeConstrainedMappingJackson2HttpMessageConverter

Here's one way to do that, where we add the Converter to our existing list of Message Converters. Notice the halJacksonHttpMessageConverter qualifier. That's essential as it is a Spring RepositoryRestMvcConfiguration component.

Using the RestTemplate

We'll go to our Tests and see the HAL-enhanced RestTemplate at work where we first retrieve a List of Post Objects. We pull our Post Resources from our ResponseEntity Body, then the Posts from Resources Content.

Here we retrieve an individual Post object.

Source Code Notes for this Post

Source code discussed in our Spring Cloud Series is found in NixMash Sping Cloud on GitHub. Code for this particular post is found in branch nixmashcloud-v0.1.0 - Initial Layout and Structure.

Posted June 01, 2017 11:26 AM EDT

More Like This Post