java - RestController - 在反序列化 POJO 中使用 @DateTimeFormat

标签 java spring datetime spring-restcontroller

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

已关注 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) {

我创建了一个 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 端点

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

但是我的开始日期为空

  • 其他参数运行正常(日期除外)

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

最佳答案

尝试@JsonDeserialize

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

DateHandler 类

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

}

供引用How to deserialize Date from JSON using Jackson

关于java - RestController - 在反序列化 POJO 中使用 @DateTimeFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56766345/

相关文章:

java - CountTimer 无法解析为类型

java - 获取 POI 中特定行中填充的单元格数量的计数

java - 嵌套循环中的随机不同数字

spring security 5.1 oauth 2,如何向用户身份验证uri添加附加参数

sql - 配置 SQL Server 以存储 UTC 日期时间

java - 获取 JAR 文件的位置

java - Spring 数据 jpa。返回 Map 作为 group by 操作的结果

java - spring boot 集成测试 - 数据库未使用 @WebMvcTest Autowiring

c# - 如何格式化 DateTime 或 TimeZone/TimeZoneInfo 以显示三个字母?

python - 有效解析文本文件的日期时间