Spring Data 2.X中Page的Sort无法正确序列化为JSON的解决咨询
解决Spring Data 2.x中Page返回JSON缺失完整Sort信息的问题
我之前也碰到过完全一样的问题!在Spring Data 2.x版本里,Page对象序列化后的JSON中,sort字段确实只保留了sorted和unsorted两个布尔值,不像1.x那样会输出排序方向、属性名这些完整细节。这是因为Spring Data 2.x对Sort的默认序列化逻辑做了简化调整,不过我们可以通过自定义Jackson序列化器来恢复旧的输出格式。
下面是具体的解决步骤:
自定义Jackson序列化模块
我们可以创建一个自定义的Jackson模块,专门处理Sort类的序列化,把所有排序相关的细节都输出到JSON中:
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Component; import java.io.IOException; @Component public class SortJacksonModule extends SimpleModule { public SortJacksonModule() { // 注册自定义的Sort序列化器 addSerializer(Sort.class, new SortSerializer()); } static class SortSerializer extends JsonSerializer<Sort> { @Override public void serialize(Sort sort, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); // 保留默认的两个布尔字段 gen.writeBooleanField("sorted", sort.isSorted()); gen.writeBooleanField("unsorted", sort.isUnsorted()); // 如果有排序规则,输出完整的Order细节 if (sort.isSorted()) { gen.writeFieldName("sort"); gen.writeStartArray(); for (Sort.Order order : sort) { gen.writeStartObject(); gen.writeStringField("direction", order.getDirection().name()); gen.writeStringField("property", order.getProperty()); gen.writeBooleanField("ignoreCase", order.isIgnoreCase()); gen.writeStringField("nullHandling", order.getNullHandling().name()); gen.writeBooleanField("ascending", order.isAscending()); gen.writeBooleanField("descending", order.isDescending()); gen.writeEndObject(); } gen.writeEndArray(); } gen.writeEndObject(); } } }
原理说明
这个自定义模块会被Spring自动扫描并注册到Jackson的ObjectMapper中,当序列化Sort对象时,就会使用我们自定义的序列化逻辑,把每个Sort.Order的详细信息都输出到JSON数组里,和Spring Data 1.x的输出格式完全一致。
验证效果
现在再访问你的/sorttest接口,返回的JSON里sort字段就会恢复成你熟悉的完整格式:
{ "content": [1], "pageable": { "sort": { "sorted": true, "unsorted": false, "sort": [ { "direction": "ASC", "property": "asdf", "ignoreCase": false, "nullHandling": "NATIVE", "ascending": true, "descending": false } ] }, "pageNumber": 0, "pageSize": 5, "offset": 0, "paged": true, "unpaged": false }, "totalElements": 1, "totalPages": 1, "last": true, "size": 5, "number": 0, "sort": { "sorted": true, "unsorted": false, "sort": [ { "direction": "ASC", "property": "asdf", "ignoreCase": false, "nullHandling": "NATIVE", "ascending": true, "descending": false } ] }, "first": true, "numberOfElements": 1, "empty": false }
内容的提问来源于stack exchange,提问作者Oleg Danyliuk
相关产品推荐
相关产品推荐

