PageImpl在springboot中的JSON序列化问题
(1) 返回的结果在springboot 1.x 和 springboot 2.x中不一致
例如以下API
@RestControllerpublic class SomeController {
@GetMapping
public PageImpl listAll() {
...
}
}
在springboot 1.x中的结果:
{ "content": [
{...},
{...},
....
],
"totalElements": 50,
"totalPages": 3,
"last": false,
"size": 20,
"number": 0,
"numberOfElements": 1,
"first": true,
"sort": [
{
"direction": "DESC",
"property": "date",
"ignoreCase": false,
"nullHandling": "NATIVE",
"ascending": false,
"descending": true
}
]
}
然而在springboot 2.x中的结果除了content的内容相同,其他的内容都有很大的差别:
{ "content": [
{...},
{...},
....
],
"pageable": {
"sort": {
"sorted": true,
"unsorted": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 20,
"paged": true,
"unpaged": false
},
"totalPages": 3,
"last": false,
"totalElements": 50,
"size": 20,
"number": 0,
"numberOfElements": 1,
"sort": {
"sorted": true,
"unsorted": false
},
"first": true
}
怎么样才能在springboot2的结果和springboot1的一致呢?下面通过jackson自定义反序列实现
import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import java.io.IOException;
@JsonComponent
public class PageImplJacksonSerializer extends JsonSerializer {
@Override
public void serialize(PageImpl page, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField("content", page.getContent());
jsonGenerator.writeBooleanField("first", page.isFirst());
jsonGenerator.writeBooleanField("last", page.isLast());
jsonGenerator.writeNumberField("totalPages", page.getTotalPages());
jsonGenerator.writeNumberField("totalElements", page.getTotalElements());
jsonGenerator.writeNumberField("numberOfElements", page.getNumberOfElements());
jsonGenerator.writeNumberField("size", page.getSize());
jsonGenerator.writeNumberField("number", page.getNumber());
Sort sort = page.getSort();
jsonGenerator.writeArrayFieldStart("sort");
for (Sort.Order order : sort) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("property", order.getProperty());
jsonGenerator.writeStringField("direction", order.getDirection().name());
jsonGenerator.writeBooleanField("ignoreCase", order.isIgnoreCase());
jsonGenerator.writeStringField("nullHandling", order.getNullHandling().name());
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
}
}
以上是 PageImpl在springboot中的JSON序列化问题 的全部内容, 来源链接: utcz.com/z/514303.html