Spring Boot-如何为“ java.time.LocalDateTime”类创建自定义序列化

时间:2018-07-28 16:46:44

标签: java json spring-boot web jackson

我已经使用Spring Boot开发了一个REST服务。我想返回一个以用户生日为毫秒的json响应。 如何将java.time.LocalDateTime对象序列化为毫秒?

我的模型班:

    @Entity(name = "users")
    public class User implements Serializable {

        @Id
        @GeneratedValue
        @Column(name = "user_id")
        private Long id;

        @Column(name = "first_name")
        private String firstName;

        @Column(name = "last_name")
        private String lastName;



        @Column(name = "date_of_birth")
        private LocalDateTime dateOfBirth;  

 . . .

    }

当前响应:

{
 . . .
"dateOfBirth":[2018,7,25,7,0],
. . . 
}

首选回复:

{
 . . .
"dateOfBirth": 1532786354419,
. . . 
}

3 个答案:

答案 0 :(得分:2)

使用@JsonSerialize(using = CustomSerializer.class)

@Entity(name = "users")
public class User implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;


    @JsonSerialize(using = CustomSerializer.class)
    @Column(name = "date_of_birth")
    private LocalDateTime dateOfBirth;  

    . . .

}

自定义Serilizer类:

public class CustomSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    //add your custom date parser
    gen.writeString(value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+"");
}
}

答案 1 :(得分:0)

为什么不存储以下日期属性:

@Temporal(TemporalType.TIMESTAMP)
private Date date = new Date();

以毫秒为单位给出日期。将其格式化为所需的输出是应用程序层的责任。不要对带有某些注释的实体本身执行此操作。

答案 2 :(得分:0)

如果您不想用@JsonSerialize装饰所有对象,则可以将对象映射器配置为始终返回LocalDateTime的long。

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateSerializer());
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateDeserializer());
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
}

以及解序列器和序列化器。

public class LocalDateSerializer extends JsonSerializer<LocalDateTime> {
    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(String.valueOf(value.atZone(ZoneId.systemDefault()).toEpochSecond()));
    }
}

public class LocalDateDeserializer extends JsonDeserializer<LocalDateTime> {
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(p.getValueAsString())), ZoneId.systemDefault());
    }
}

在您的示例中,您使用的出生日期可能是LocalDate