问题描述
我正在开发基于 Spring Data REST 的服务.由于我们使用 swagger(通过 SpringFox 生成)创建前端代码这一事实,我不得不停用 HAL 格式的返回,该格式可以正常工作,但有一个例外.
I am developing a Service based on Spring Data REST. Cause of the fact that we are creating the frontend code using swagger (generated via SpringFox) I had to deactivate the return of the HAL-format which works fine with one exception.
如果请求的结果是一个空列表,则响应如下
If the result of a request is an empty list the response looks like this
{
"links": [
{
"rel": "self",
"href": "http://localhost:9999/users"
},
{
"rel": "profile",
"href": "http://localhost:9999/profile/users"
}
],
"content": [
{
"rel": null,
"collectionValue": true,
"relTargetType": "com.example.User",
"value": []
}
]
}
如何获取空列表作为内容?
How can I get an empty List as content?
推荐答案
为了使用 Spring HATEOAS 1.x 引入的类型,我不得不调整上一个解决方案中提供的解决方案
I have had to adapt the solution provided in the previous solution to use the types introduced by the Spring HATEOAS 1.x
这是我正在使用的代码:
This is the code I'm using:
@Component
public class ResourceProcessorEmpty implements RepresentationModelProcessor<CollectionModel<Object>> {
@Override
public CollectionModel<Object> process(CollectionModel<Object> resourceToThrowAway) {
if (resourceToThrowAway.getContent().size() != 1) {
return resourceToThrowAway;
}
if (!resourceToThrowAway.getContent().iterator().next().getClass().getCanonicalName().contains("EmptyCollectionEmbeddedWrapper")) {
return resourceToThrowAway;
}
CollectionModel<Object> newResource = new CollectionModel<>(Collections.emptyList());
newResource.add(resourceToThrowAway.getLinks());
return newResource;
}
}
这篇关于Spring Data REST 返回 EmptyCollectionEmbeddedWrapper 而不是空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!