I have a controller with method:
@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response<Boolean> requestAppt(
@RequestBody @Valid ApptRequest request
) {
System.out.println(request);
return Response.success(true);
}
My ApptRequest is:
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.time.OffsetDateTime;
public class ApptRequest implements Serializable{
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private OffsetDateTime date;
public ApptRequest() {
}
public OffsetDateTime getDate() {
return date;
}
public void setDate(OffsetDateTime date) {
this.date = date;
}
}
When I'm trying to send a request with request body:
{
"date": "2016-05-11T13:30:38+02:00"
}
I have an exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class java.time.OffsetDateTime] from String value ('2016-05-11T13:30:38+02:00'); no single-String constructor/factory method
It says that OffsetDateTime should have a constructor or factory method with only one String parameter. But I found that it has needed factory method with CharSequence parameter:
/**
* Obtains an instance of {@code OffsetDateTime} from a text string
* such as {@code 2007-12-03T10:15:30+01:00}.
* <p>
* The string must represent a valid date-time and is parsed using
* {@link java.time.format.DateTimeFormatter#ISO_OFFSET_DATE_TIME}.
*
* @param text the text to parse such as "2007-12-03T10:15:30+01:00", not null
* @return the parsed offset date-time, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static OffsetDateTime parse(CharSequence text) {
return parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
}
And if I try to use date as request param instead of request body property everything is working correctly:
@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response<Boolean> requestAppt(
@RequestParam @Valid @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime date
) {
System.out.println(date);
return Response.success(true);
}
May be I should specify the appropriate constructor manually using some annotations or something like that?