我有带有日期参数的 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;
}
}
}
关于java - RestController - 在反序列化 POJO 中使用 @DateTimeFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56766345/