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?
You have missed
@RequestBody
in the controller, so the value is considered asQueryParam
. Add, it will work.Another thing I noticed is the date format
"dd.MM.yyyy hh:mm:ss"
, I think this is not a Valid format ofDateTimeFormatter
Valid Formats
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 likeand the change in class will be
Have also looked into formats
SimpleDateFormat
(@JsonFormat
use this foramtter), refer SimpleDateFormat - PatternsYou can try using:
and change the desired format
Try @JsonDeserialize
DateHandler class
For reference How to deserialize Date from JSON using Jackson