加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – @DateTimeFormat无法识别

发布时间:2020-12-15 04:38:31 所属栏目:Java 来源:网络整理
导读:我试图使用@DateTimeFormat注释LocalDateTime对象 为什么不承认呢? 我的主要想法是,一旦在控制器中收到一个字符串,它就会将其转换为LocalDateTime对象 目前我得到了: { "timestamp": 1493708443198,"status": 400,"error": "Bad Request","exception": "or
我试图使用@DateTimeFormat注释LocalDateTime对象
为什么不承认呢?

我的主要想法是,一旦在控制器中收到一个字符串,它就会将其转换为LocalDateTime对象

enter image description here

目前我得到了:

{
  "timestamp": 1493708443198,"status": 400,"error": "Bad Request","exception": "org.springframework.http.converter.HttpMessageNotReadableException","message": "Could not read JSON document: Can not construct instance of java.time.LocalDateTime: no String-argument constructor/factory method to deserialize from String value ('2015-09-26T01:30:00.000')n at [Source: java.io.PushbackInputStream@3233297a; line: 5,column: 23] (through reference chain: net.petrikainulainen.spring.trenches.model.Topic["localDateTime"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDateTime: no String-argument constructor/factory method to deserialize from String value ('2015-09-26T01:30:00.000')n at [Source: java.io.PushbackInputStream@3233297a; line: 5,column: 23] (through reference chain: net.petrikainulainen.spring.trenches.model.Topic["localDateTime"])","path": "/api/topics"
}

当试图发布

{
     "id": "javaw2","name": "java code","descript2ion": "java description","localDateTime": "2015-09-26T01:30:00.000"
 }

这是我的控制器:

@RequestMapping(method = RequestMethod.POST,value = "/topics")
public void addTopic(@RequestBody Topic topic) {
    topicService.addTopic(topic);
}

解决方法

Can not construct instance of java.time.LocalDateTime: no String-argument constructor/factory method to deserialize from String value (‘2015-09-26T01:30:00.000’)

该错误表明LocalDateTime类没有String参数构造函数/工厂方法,因此您必须编写自己的反序列化器以将Date字符串表示反序列化为LocalDateTime Object.

就像是 :

@JsonDeserialize(using = MyDateDeserializer.class)
private LocalDateTime localDateTime;

然后MyDateDeserializer实现

public class MyDateDeserializer extends JsonDeserializer< LocalDateTime > {
  @Override
  public LocalDateTime deserialize(JsonParser jp,DeserializationContext ctxt) throws Exception {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("your pattern");

    String date = jp.getValueAsString();

    LocalDateTime localDateTime = LocalDateTime.parse(date,formatter);
    return localDateTime;
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读