Question

I have a web application in which i use Spring MVC with Spring Hateoas with HypermediaType HAL. In my Controller i use the Resources Class to put in a list of Subjects. The problem is, that if i put in a list of one element, the structure of the resulting json distinguishes from if i put in 2 elements. If the list only contains one element it removes the list and returns it as a single object. Below the two Controller methods i pasted the resulting Json.

I now want to know, why the behavior is like that and how can i force Hateoas to use a list in the resulting json?

@Controller
@RequestMapping(value = "/collections")
public class CollectionController {

    @RequestMapping
    public HttpEntity<Resources<Subject>> getOneSubject() {

        Subject subject = new Subject();
        Resources<Subject> subjects = new Resources<>(asList(subject));

        return new ResponseEntity<>(subjects, HttpStatus.OK);
    }
/*HTTP-Response Body:
{
    "_embedded": {
        "subject": {
            "name": null
        }
    }
}
*/


    @RequestMapping
    public HttpEntity<Resources<Subject>> getTwoSubjects() {

        Subject subject = new Subject();
        Resources<Subject> subjects = new Resources<>(asList(subject, subject));

        return new ResponseEntity<>(subjects, HttpStatus.OK);
    }
/*HTTP-Response Body:
{
    "_embedded": {
        "subjectList": [
            {
                "name": null
            },
            {
                "name": null
            }
        ]
    }
}*/

}

Hateoas configuration:

@Configuration
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class HateoasConfig {
}
Was it helpful?

Solution

I can get the example project you provided to run after the following steps:

  1. Upgrade to a compatible Jackson version (2.3.0 or better). Use Spring HATEOAS 0.10.0.BUILD-SNAPSHOT.
  2. Run the app.
  3. curl -v -H "Accept: application/hal+json" http://localhost:8080/api/subjects

Result:

* Adding handle: conn: 0x7fc072803a00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fc072803a00) send_pipe: 1, recv_pipe: 0
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /api/subjects HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:8080
> Accept: application/hal+json
> 
< HTTP/1.1 200 OK
< Content-Type: application/hal+json
< Transfer-Encoding: chunked
* Server Jetty(8.1.14.v20131031) is not blacklisted
< Server: Jetty(8.1.14.v20131031)
< 
* Connection #0 to host localhost left intact
{"_links":{"self":{"href":"http://localhost:8080/api/subjects"}},"_embedded":{"subjectList":[{"name":"foo"}]}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top