SpringBoot+ElasticSearch关于返回Page对象异常处理

在整合springboot和elasticsearch过程中,一个分页方法响应时出现了json转换异常,当前springboot版本为1.5.3,elasticsearch中jar版本2.4.4

异常信息

首先来看服务器返回的错误

1
Could not write JSON document: (was java.lang.NullPointerException) (through reference chain: org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl["facets"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl["facets"])

1
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON document: (was java.lang.NullPointerException) (through reference chain: org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl["facets"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl["facets"])

异常代码

代码中主要就是实现es分页搜索,返回一个Page对象

1
2
3
4
@GetMapping("/page")
public Page<ElianPrice> page(ElianPrice elianPrice,int page,int size){
return elianPriceService.pageSearch(elianPrice, page, size);
}

解决方法

经过debug发现错误是发生在spring序列化Page对象的时候发生的。经过查询资料,在stackoverflow上提供了解决方法,就是直接返回content内容回去。

1
2
3
4
@GetMapping("/page")
public List<ElianPrice> page(ElianPrice elianPrice,int page,int size){
return elianPriceService.pageSearch(elianPrice, page, size).getContent();
}

这样虽然没有错误了,但是显然与我想要的分页还是有区别。再次搜索资料,找到一个更好的解决方法,
DATAES-274
这里提供转换的方法,把原来的Page转换下

1
2
3
4
5
6
7
8
9
10
11
private <T> Page<T> fixEmptyPage(Page<T> page) {
AggregatedPageImpl<T> aggregatedPage = (AggregatedPageImpl<T>) page;
Aggregations aggregations = aggregatedPage.getAggregations();
if (aggregations == null) {
Field field = ReflectionUtils.findField(AggregatedPageImpl.class, "aggregations");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, aggregatedPage, InternalAggregations.EMPTY);
return aggregatedPage;
}
return page;
}

这样同样不会再出现问题了,问题解决。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×