Java – @ datetimeformat not recognized

I tried to annotate a localdatetime object with @ datetimeformat

My main idea is that once a string is received in the controller, it will convert it to a localdatetime object

Now I have:

{
  "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"
}

When trying to publish

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

This is my controller:

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

Solution

This error indicates that the localdatetime class does not have a string parameter constructor / factory method, so you must write your own deserializer to deserialize the date string representation to localdatetime object

It's like:

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

Then mydatedeserializer is implemented

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;
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>