我試圖使用@DateTimeFormat注釋LocalDateTime物件為什么不承認呢?
我的主要想法是,一旦在控制器中收到一個字串,它就會將其轉換為LocalDateTime物件

目前我得到了:
{
"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);
}
uj5u.com熱心網友回復:
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;
}
}
uj5u.com熱心網友回復:
SSM框架:使用Date代替LocalDateTime,結合@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss"),可以接收到@RequestBody中的時間字串,
并轉型為Date型yyyy-MM-dd HH:mm:ss的時間格式,
SpringBoot框架:
可以正常使用LocalDateTime.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/19691.html
標籤:其他技術討論專區
上一篇:求教
下一篇:mqtt服務器一直連接失敗
