我有一个Web应用程序,其中我使用带有HypermediaType HAL的Spring Hateoas的Spring MVC。在我的Controller中,我使用Resources Class放入Subjects列表。 问题是,如果我放入一个元素的列表,结果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 {
}
答案 0 :(得分:1)
我可以在以下步骤之后获得您提供的示例项目:
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"}]}}