RestController-在反序列化的POJO中使用@DateTimeFormat [英] RestController - Use @DateTimeFormat inside deserialized POJO

查看:349
本文介绍了RestController-在反序列化的POJO中使用@DateTimeFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要反序列化的日期参数的JSON正文

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

在Spring中使用日期参数


用@DateTimeFormat注释对参数进行注释,然后提供格式设置模式参数:

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

我们还可以使用自己的转换模式。我们可以在@DateTimeFormat批注中提供模式参数:

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) {


我创建了一个POJO

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;

我的RestController端点

My RestController endpoint

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

我发布数据:

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

但是我的startDate为空

But my startDate is null


  • 其他参数正常工作(日期除外)

我可以在Object内使用 @DateTimeFormat 还是必须像示例中那样声明所有参数?

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

推荐答案

尝试@JsonDeserialize

Try @JsonDeserialize

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

DateHandler类

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

}

供参考如何使用杰克逊从JSON反序列化日期

这篇关于RestController-在反序列化的POJO中使用@DateTimeFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆