SpringBoot全局处理LocalDateTime返回格式和Long类型序列化
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeSerializer extends StdScalarSerializer<LocalDateTime> {
private static final long serialVersionUID = 1L;
private final DateTimeFormatter formatter;
protected LocalDateTimeSerializer(DateTimeFormatter formatter) {
super(LocalDateTime.class);
this.formatter = formatter;
}
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(formatter.format(value));
}
// 自定义LongSerializer
public static class LongSerializer extends StdScalarSerializer<Long> {
private static final long serialVersionUID = 1L;
protected LongSerializer() {
super(Long.class);
}
@Override
public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
if (value == null) {
gen.writeString("");
} else {
gen.writeNumber(value);
}
}
}
}
在Spring Boot中,你可以在配置类中添加如下配置来使用这个自定义的序列化器:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializers;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 禁用默认的序列化特性
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 自定义LocalDateTime的序列化格式
mapper.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// 自定义Long类型序列化器
mapper.serializerProvider().addValueSerializer(Long.class, new LocalDateTimeSerial
评论已关闭