gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:42:36 26 4
gpt4 key购买 nike

我用 Spring Boot 开发了一个休息服务。我想返回一个以毫秒为单位的用户生日的 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,
. . .
}

最佳答案

使用 @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;

. . .

}

自定义序列化器类:

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()+"");
}
}

关于java - Spring Boot - 如何为 "java.time.LocalDateTime"类创建自定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com