我有一个方法控制器:
@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response<Boolean> requestAppt(
@RequestBody @Valid ApptRequest request
) {
System.out.println(request);
return Response.success(true);
}
我的ApptRequest是:
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;
}
}
当我尝试向请求正文发送请求时:
{
"date": "2016-05-11T13:30:38+02:00"
}
我有一个例外:
org.springframework.http.converter.HttpMessageNotReadableException: 无法读取文档:无法实例化类型的值[简单 来自String值的type,class java.time.OffsetDateTime] (&#39; 2016-05-11T13:30:38 + 02:00&#39);没有单字符串构造函数/工厂 方法
它表示 OffsetDateTime应该只有一个String参数的构造函数或工厂方法。 但我发现它需要带有CharSequence参数的工厂方法:
/**
* 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);
}
如果我尝试将日期用作请求参数而不是请求正文属性,一切正常:
@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);
}
可能我应该使用一些注释或类似的东西手动指定适当的构造函数?
答案 0 :(得分:1)
将数据类型:jackson-datatype-jsr310添加到classpath应该会有所帮助。灵感来自JSON Java 8 LocalDateTime format in Spring Boot