SpringBoot中自定义类型转换(以LocalDateTime为例)

Jackson


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author Qbit
 */
@Slf4j
@Configuration
public class JacksonConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
        log.info("use "+Jackson2ObjectMapperBuilderCustomizer.class.getSimpleName()+" from "+JacksonConfig.class.getName());
        return jacksonObjectMapperBuilder -> {
            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, LocalDateTimeSerializer.getInstance());
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, LocalDateTimeDeserializer.getInstance());
            jacksonObjectMapperBuilder.deserializerByType(LocalTime.class,new LocalDateTimeDeserializer());
        };
    }

    /**
     * @author Qbit
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        private static final LocalDateTimeDeserializer INSTANCE = new LocalDateTimeDeserializer();

        public static LocalDateTimeDeserializer getInstance() {
            return INSTANCE;
        }

        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            return LocalDateTime.parse(jsonParser.getValueAsString(),DateTimeFormatters.yyyy_MM_dd_HH_mm_ss);
        }
    }
    public static class LocalTimeDeserializer extends JsonDeserializer<LocalTime> {

        @Override
        public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            return Transformers.toLocalTime(jsonParser.getValueAsString());
        }
    }
    /**
     * @author Qbit
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        private static final LocalDateTimeSerializer INSTANCE=new LocalDateTimeSerializer();
        public static LocalDateTimeSerializer getInstance() {
            return INSTANCE;
        }

        @Override
        public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(localDateTime.format(DateTimeFormatters.yyyy_MM_dd_HH_mm_ss));
        }
    }
}

SpringBoot默认使用的Jackson来做json格式的转换,所以将自己对特定格式的转换类注册进去。

Converter

需要注意的是上面的只针对入参和出参是json格式时生效,如果入参是Paramenter则不会生效,这时需要提供自定的Converter

LocalDateTimeConverter

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    @Override
    public LocalDateTime convert(String s) {
        return Transformers.toLocalDateTime(s);
    }
}

工具类

public class Transformers {
    public static DateTimeFormatter yyyy_MM_dd_HH_mm_ss=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static DateTimeFormatter HH_mm_ss=DateTimeFormatter.ofPattern("HH:mm:ss");

    public static LocalDateTime toLocalDateTime(String s) {
        return LocalDateTime.parse(s, yyyy_MM_dd_HH_mm_ss);
    }

    public static LocalTime toLocalTime(String s) {
        return LocalTime.parse(s, HH_mm_ss);
    }
}
在使用 Spring Data MongoDB 操作 MongoDB 数据库时,可以使用 @Field 注解来指定实体类的属性与 MongoDB 的字段之间的映射关系。当实体类的属性类型为 LocalDateTime 时,可以使用 @Field 注解的 converter 属性来指定一个自定义的转换器,将 LocalDateTime 转换成 Date 类型。 具体代码如下: ```java import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.convert.converter.Converter; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date; @Document(collection = "myCollection") public class MyEntity { @Id private String id; @Field(value = "myDate") private LocalDateTime myDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public LocalDateTime getMyDate() { return myDate; } public void setMyDate(LocalDateTime myDate) { this.myDate = myDate; } public static class LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> { @Override public Date convert(LocalDateTime localDateTime) { return Date.from(localDateTime.toInstant(ZoneOffset.UTC)); } } } ``` 在这个例子,我们使用 @Field 注解将实体类的 myDate 属性映射到 MongoDB 的 myDate 字段,并使用 converter 属性指定 LocalDateTimeToDateConverter 类型的转换器,将 LocalDateTime 转换成 Date 类型。在转换器,我们使用 LocalDateTime 的 toInstant() 方法将其转换成 Instant 类型,然后再使用 Date.from() 方法将其转换成 Date 类型,最后存储到 MongoDB 。 注意:需要在 Spring Boot 应用程序启动类注册该转换器,例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import java.util.Arrays; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public MongoCustomConversions mongoCustomConversions() { return new MongoCustomConversions(Arrays.asList(new MyEntity.LocalDateTimeToDateConverter())); } } ``` 在启动类,我们创建一个 MongoCustomConversions 类型的 Bean,并将 LocalDateTimeToDateConverter 类型的转换器注册进去。这样 Spring Data MongoDB 就会自动地调用该转换器,将 LocalDateTime 类型的数据转换成 Date 类型,并存储到 MongoDB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值