@DateTimeFormat无法识别

时间:2017-05-02 07:11:50

标签: java spring

我正在尝试使用LocalDateTime注释@DateTimeFormat个对象 为什么不承认呢?

我的主要想法是,一旦在控制器中收到一个字符串,它就会将其转换为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);
}

2 个答案:

答案 0 :(得分:4)

  

无法构造java.time.LocalDateTime的实例:no String-argument构造函数/工厂方法从String值反序列化('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;
  }
}

答案 1 :(得分:3)

您不需要使用@DateTimeFormat注释该字段,因为它已经是杰克逊认可的格式。您需要做的就是将JavaTimeModule添加到ObjectMapper配置中,以便它可以将字符串反序列化为LocalDateTime。这是一个例子:

<强>型号:

class Model {
    private LocalDateTime date;

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }
}

<强>反序列化

public static void main(String[] args) throws Exception {
    String json = "{\"date\" : \"2015-09-26T01:30:00.000\"}";
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());

    Model model = mapper.readValue(json, Model.class);
    System.out.println(model.getDate());
}

为此,您必须使用Jackson 2.8.5或更高版本,here's文档。