Java 实体类 LocalDateTime 返回前端指定格式
在 Java 的实体类中,如果想要将 LocalDateTime 对象返回给前端,并指定特定的格式,可以使用 @JsonFormat 注解,指定日期时间的格式。
例如,假设有一个实体类 User,包含一个 LocalDateTime 类型的属性 createDate,我们希望返回给前端的日期时间格式为 'yyyy-MM-dd HH:mm:ss',可以这样写代码:
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
public class User {
private LocalDateTime createDate;
// 其他属性和方法...
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDateTime createDate) {
this.createDate = createDate;
}
}
在上面的代码中,通过在 getCreateDate() 方法上使用 @JsonFormat 注解,并指定 pattern 为 'yyyy-MM-dd HH:mm:ss',就可以将 LocalDateTime 对象以指定的格式返回给前端。
当使用 Spring Boot 框架时,如果使用 @RestController 注解标记了控制器类,并且返回的实体类是通过 Jackson 库序列化为 JSON 对象的,那么 Jackson 库会自动处理 @JsonFormat 注解,并将 LocalDateTime 对象以指定的格式输出到 JSON 字符串中。
原文地址: https://www.cveoy.top/t/topic/pmz2 著作权归作者所有。请勿转载和采集!