解决LocalDateTime序列化问题
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
@Configuration
public class JsonSerializationConfigurer {
public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern(PATTERN);
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.setDateFormat(new SimpleDateFormat(PATTERN))
.registerModule(new SimpleModule()
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATE_TIME))
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATE_TIME))
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer2())
.addSerializer(Long.class, new CustomNumberSerializer())
);
}
/**
* 数字类型的序列化方式,超过js环境安全值转成字符串给到前端,其他的保持原样
*/
public static class CustomNumberSerializer extends JsonSerializer<Number> {
@Override
public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
ToStringSerializer.instance.serialize(value, gen, serializers);
}
}
public static class LocalDateTimeDeserializer2 extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException {
long timestamp = p.getValueAsLong();
if (timestamp > 0) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
} else {
return null;
}
}
}
}