Timi
Timi

Reputation: 844

HAL-style rendering issues with spring-hateoas

This time I'm really confused and stuck... I'm working on a spring-boot (1.5.3) application exposing a REST API with HAL style using spring-hateoas library. Some of the endpoints already work correctly and return HAL-links. Currently I'm trying to change another endpoint to also return the response with HAL, but the result is serialized in the "collection+json" style.

What I found so far: There are 3 ObjectMapper instances in the spring context:

I converted the response with all three of these and found that the first two produce "collection+json" output ("links" with "rel") and the third one produces the expected HAL style ("_links" without "rel").

Why are there three and how can I inspect and control which of these objectMappers get used for rendering the response? How is it possible that my other endpoints return the expected format?


Here's my simplified code, in case it's of any interest:

@RestController
public class SearchController{

    @RequestMapping(value = "/search", produces = { "application/hal+json" }, method = RequestMethod.GET)
    public ResponseEntity<SearchResponse> search(...){
        SearchResponse searchResponse = ...; // search & build response
        return new ResponseEntity<>(searchResponse, HttpStatus.OK);
    }
}

public class SearchResponse {

    @JsonProperty("_meta")
    private PageSortInfo meta;

    @JsonUnwrapped
    private Resources<Resource<SearchResultItem>> resultlist;

    ...// getters & setters
}

The response is supposed to look like this:

{
    "_meta" : {
      ...
    },
    "_embedded" : {
      "searchResultItemList" : [ {
        ...,
        "_links" : {
          "self" : {
            "href" : "..."
          }
        }
      },
      ...
      ]
    },
    "_links" : {
      "self" : {
        "href" : "http://localhost:8882/api/search"
      }
    }
}

Upvotes: 1

Views: 920

Answers (1)

Timi
Timi

Reputation: 844

Well, after another day of digging through google search results, sprint-boot code and a lot of trial & error I finally found the answer, which is of course trivial:

Spring will choose the MessageConverter used to convert the response object to the appropriate format by matching the registered converters to the type of the object (in my case SearchResponse) and the response type ("application/hal+json" for me). The halJacksonHttpMessageConverter will only be chosen if the response object is of type ResourceSupport. SO all I had to do is make my SearchResponse extend ResourceSupport and I got the expected response format.

public class SearchResponse extends ResourceSupport {...}

Upvotes: 1

Related Questions