gpt4 book ai didi

java - @DateTimeFormat 无法识别

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:21:51 27 4
gpt4 key购买 nike

我正在尝试使用 @DateTimeFormat 注释 LocalDateTime 对象为什么它不识别它?

我的主要想法是,一旦 Controller 接收到一个字符串,它就会将其转换为 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"
}

这是我的 Controller :

@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 对象。

类似的东西:

@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;
}
}

关于java - @DateTimeFormat 无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43732143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com