使用Spring Boot框架时,可以通过Jackson库来自定义日期的序列化和反序列化行为。详细代码
时间: 2024-09-09 07:11:31 浏览: 83
在Spring Boot框架中,Jackson库默认使用`java.util.Date`和`java.sql.Timestamp`类的序列化和反序列化行为。如果你需要自定义这些日期格式,可以通过定义`@JsonComponent`或者使用`ObjectMapper`来自定义转换器。下面是一个使用`@JsonComponent`来自定义日期序列化和反序列化的示例代码:
```java
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonSerializerCustomizer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@JsonComponent
public class CustomDateSerializer extends StdSerializer<Date> {
private static final long serialVersionUID = 1L;
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(Class<Date> t) {
super(t);
}
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {
String formattedDate = formatter.format(value);
gen.writeString(formattedDate);
}
}
public class CustomDateDeserializer extends StdSerializer<Date> {
private static final long serialVersionUID = 1L;
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<Date> t) {
super(t);
}
@Override
public Date deserialize(JsonParser p, SerializerProvider ctxt) throws IOException, JsonProcessingException {
String date = p.getText();
try {
return formatter.parse(date);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// 在你的Date字段上使用@JsonSerialize注解
class MyEntity {
@JsonSerialize(using = CustomDateSerializer.class)
private Date date;
// ...
}
```
在上面的代码中,`CustomDateSerializer`和`CustomDateDeserializer`类分别定义了自定义序列化和反序列化行为。`SimpleDateFormat`用于定义日期格式。`@JsonComponent`注解告诉Spring Boot自动注册这个组件。在你的实体类中的日期字段上,可以使用`@JsonSerialize`注解来指定使用你的自定义序列化器。
如果你不想使用`@JsonComponent`,也可以直接在配置类中配置`ObjectMapper`:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new CustomDateSerializer());
module.addDeserializer(Date.class, new CustomDateDeserializer());
mapper.registerModule(module);
return mapper;
}
}
```
在`JacksonConfig`配置类中,我们定义了一个`ObjectMapper` Bean,为其添加了自定义的日期序列化器和反序列化器。
阅读全文