0

我有一个 Web 应用程序,我在其中使用 Spring MVC 和带有 HypermediaType HAL 的 Spring Hateoas。在我的控制器中,我使用资源类来放入主题列表。问题是,如果我放入一个元素的列表,则生成的 json 的结构与我放入 2 个元素的结构不同。如果列表只包含一个元素,它将删除列表并将其作为单个对象返回。在两个 Controller 方法下方,我粘贴了生成的 Json。

我现在想知道,为什么会出现这样的行为以及如何强制 Hateoas 在生成的 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
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class HateoasConfig {
}
4

1 回答 1

1

我可以在以下步骤之后运行您提供的示例项目:

  1. 升级到兼容的 Jackson 版本(2.3.0 或更高版本)。使用 Spring HATEOAS 0.10.0.BUILD-SNAPSHOT。
  2. 运行应用程序。
  3. curl -v -H "Accept: application/hal+json" http://localhost:8080/api/subjects

结果:

* 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"}]}}
于 2014-03-25T13:15:26.243 回答