SpringBoot 2.2.2:用于自定义分页的 Jackson 序列化程序不起作用
Posted
技术标签:
【中文标题】SpringBoot 2.2.2:用于自定义分页的 Jackson 序列化程序不起作用【英文标题】:SpringBoot 2.2.2: Jackson serializer for custom pagination doesn't work 【发布时间】:2020-04-11 11:17:06 【问题描述】:从 SpringBoot 2.2.2 开始,带有 Jackson (2.10.1) 的自定义分页序列化程序不起作用,并且在序列化时不执行。
/**
* This class allows to specify configuration related to the Web MVC part.
*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer
private static final String JSON_DATA_PROPERTY = "data";
/**
* Allows to configure a @link JsonSerializer for pagination.
*
* @return an instance of @link Module.
*/
@SuppressWarnings("rawtypes")
@Bean
public Module springDataPageModule()
return new SimpleModule().addSerializer(Page.class, new JsonSerializer<Page>()
@Override
public void serialize(final Page page, final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(JSON_DATA_PROPERTY, page.getContent());
jsonGenerator.writeObjectFieldStart("paging");
jsonGenerator.writeNumberField("page", page.getNumber() + 1);
jsonGenerator.writeNumberField("totalPages", page.getTotalPages());
jsonGenerator.writeNumberField("totalElements", page.getTotalElements());
jsonGenerator.writeNumberField("perPage", page.getSize());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
);
...
在 SpringBoot 2.2.1 中,这个自定义分页序列化器被应用并工作。 你能看出这个问题吗?
【问题讨论】:
【参考方案1】:自 SpringBoot 2.2.2 以来,该行为发生了变化。 您必须通过模块的注册
/**
* This class allows to specify configuration related to the Web MVC part.
*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer
private static final String JSON_DATA_PROPERTY = "data";
/**
* Allows to configure a @link JsonSerializer for pagination.
*
* @return an instance of @link Module.
*/
private Module preparePageModule()
return new SimpleModule().addSerializer(Page.class, new JsonSerializer<>()
@Override
public void serialize(@SuppressWarnings("rawtypes") final Page page, final JsonGenerator jsonGenerator,
final SerializerProvider serializers) throws IOException
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(JSON_DATA_PROPERTY, page.getContent());
jsonGenerator.writeObjectFieldStart("paging");
jsonGenerator.writeNumberField("page", page.getNumber() + 1);
jsonGenerator.writeNumberField("totalPages", page.getTotalPages());
jsonGenerator.writeNumberField("totalElements", page.getTotalElements());
jsonGenerator.writeNumberField("perPage", page.getSize());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
);
/**
* Allows to configure the Jackson object mapper.
*
* @param objectMapper
* an instance of @link ObjectMapper.
*/
@Autowired
public void configureJacksonObjectMapper(final ObjectMapper objectMapper)
...
objectMapper.registerModule(preparePageModule());
...
`
【讨论】:
以上是关于SpringBoot 2.2.2:用于自定义分页的 Jackson 序列化程序不起作用的主要内容,如果未能解决你的问题,请参考以下文章