BlackChen'site

SpringBoot LocalDateTime返回时间戳

SpringBoot LocalDateTime返回时间戳

问题

前端同事需要使用时间戳进行时间交互. 后端使用的时间字段是LocalDateTime.

解决方案

自定义序列化与反序列化实现类. 实现自定义序列化, 返回时间戳,并接受时间戳转换为LocalDateTime


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 java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class CustomLocalDateTime {

    public static class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+"");
        }
    }

    public static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime>{
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            long timestamp = jsonParser.getValueAsLong();
            if (timestamp > 0){
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),ZoneId.systemDefault());
            }else{
                return null;
            }
        }
    }
}

实体对象使用时,在对应的字段上使用注解,指定自定义序列化与反序列化类

    @JsonDeserialize(using = CustomLocalDateTime.CustomLocalDateTimeDeserializer.class)
    @JsonSerialize(using =  CustomLocalDateTime.CustomLocalDateTimeSerializer.class)
    private LocalDateTime endTime;

评论