RestController - Use @DateTimeFormat inside deserialized POJO

て烟熏妆下的殇ゞ 提交于 2019-12-11 06:19:58

问题


I have JSON body with date parameters that I need to deserialized

Following Working with Date Parameters in Spring

annotate the parameters with the @DateTimeFormat annotation and provide a formatting pattern parameter:

We can also use our own conversion patterns. We can just provide a pattern parameter in the @DateTimeFormat annotation:

@PostMapping("/date")
public void date(@RequestParam("date") 
   @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) {

I created a POJO

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RequestVO {

    @DateTimeFormat(pattern = "dd.MM.yyyy hh:mm:ss")
    Date startDate;

My RestController endpoint

@PostMapping(value = "path", consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String updateDate(RequestVO requestVO) {
        logger.debug("requestVO.getStartDate()=" + requestVO.getStartDate());

I POST data:

{"startDate":"11.11.2019 11:11:11"}

But my startDate is null

  • Other parameters are working fine (except date)

Can I use @DateTimeFormat inside Object or must I declare all parameters as in example?


回答1:


Try @JsonDeserialize

 @JsonDeserialize(using = DateHandler.class)
  private Date publicationDate;

DateHandler class

class DateHandler extends StdDeserializer<Date> {

  public DateHandler() {
    this(null);
  }

  public DateHandler(Class<?> clazz) {
    super(clazz);
  }

  @Override
  public Date deserialize(JsonParser jsonparser, DeserializationContext context)
      throws IOException {
    String date = jsonparser.getText();
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      return sdf.parse(date);
    } catch (Exception e) {
      return null;
    }
  }

}

For reference How to deserialize Date from JSON using Jackson




回答2:


You have missed @RequestBody in the controller, so the value is considered as QueryParam. Add, it will work.

@PostMapping(value = "path", consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String updateDate(@RequestBody RequestVO requestVO) { // Added Request Body
        logger.debug("requestVO.getStartDate()=" + requestVO.getStartDate());
}

Another thing I noticed is the date format "dd.MM.yyyy hh:mm:ss", I think this is not a Valid format of DateTimeFormatter

Valid Formats

"yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"

Note : Might have missed some Formats but if any do edit it will be helpful to all

UPDATE

If you don't want millisec I think @DateTimeFormat won't help you, go with @JsonFormat like others suggested.But You should change the format of the request body like

{
 "startDate":"2019-11-11 11:11:11"
}

and the change in class will be

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
 Date startDate;

Have also looked into formats SimpleDateFormat (@JsonFormat use this foramtter), refer SimpleDateFormat - Patterns




回答3:


You can try using:

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
  private Date start;

and change the desired format



来源:https://stackoverflow.com/questions/56766345/restcontroller-use-datetimeformat-inside-deserialized-pojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!