在spring boot中为想要的类进行,序列化||反序列化
自定义自己的序列化||反序列化器
//以LocalDateTime为例
/*
*序列化器
*必须要继承JsonSerializer<T>
*/
@Component
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
//将localDateTime序列化为时间戳
jsonGenerator.writeNumber(localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
}
@Override
public Class<LocalDateTime> handledType() {
return LocalDateTime.class;
}
}
/*
*反序列化器
*必须要继承JsonDeserializer<T>
*/
@Component
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
//获取时间戳
long timestamp = jsonParser.getLongValue();
//将时间戳反序列化为localDateTime
return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8));
}
@Override
public Class<LocalDateTime> handledType() {
return LocalDateTime.class;
}
}
在spring boot接管MVC的类中进行配置自己的序列化||反序列化器
@Configuration
//@EnableWebMvc,全面接管springMVC,建议菜鸡不要用
public class MySpringMVConfig implements WebMvcConfigurer {
//装配自己的localDateTime序列化器
@Autowired
private LocalDateTimeSerializer localDateTimeSerializer;
//装配自己的localDateTime反序列化器
@Autowired
private LocalDateTimeDeserializer localDateTimeDeserializer;
/**
* 配置 Jackson
*
* @param converters 消息转换器
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder
.json()
// 属性为 null 时不进行序列化
.serializationInclusion(JsonInclude.Include.NON_NULL)
// 指定 LocalDateTime 序列化器
.serializers(localDateTimeSerializer)
// 指定 LocalDateTime 反序列化器
.deserializers(localDateTimeDeserializer)
.build();
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
converters.add(stringHttpMessageConverter);
}
}