LocalDateTime时间类型的前后端传值以及Jackson转换问题

文章介绍了如何在Java中使用@DateTimeFormat和@JsonFormat注解处理日期和时间的转换。当接收到请求时,Spring会按照@DateTimeFormat指定的格式转化字符串为日期对象,响应时则按照@JsonFormat的设置转化为JSON。此外,针对Java8的LocalDateTime类型,还使用了Jackson的序列化和反序列化注解@JsonSerialize及@JsonDeserialize,以避免处理LocalDateTime时出现异常,需要添加对应的模块支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UserVo{
  /**同时使用@DateTimeFormat、@JsonFormat这两个注解在接收请求时,Spring将使用@DateTimeFormat指定的格式将字符串转换为日期或时间对象,并在响应时,使用@JsonFormat指定的格式将日期或时间对象转换为特定的JSON格式。
  **/
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 
  @JsonSerialize(using = LocalDateTimeSerializer.class) // Jackson序列化
  @JsonDeserialize(using = LocalDateTimeDeserializer.class) // Jackson反序列化
  private LocalDateTime createTime;
}

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)

添加这两个注解可以解决报错(出现该异常的场景在SpEL表达式的解析中):
java.lang.IllegalArgumentException: Java 8 date/time type java.time.LocalDateTime not supported by default:
add Module “com.fasterxml.jackson.datatype:jackson-datatype-jsr310” to enable handling (through reference chain…

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值