我有以下restcontroller,并希望以 thedate=2016-08-08
格式查询控制器 .
它应该自动转换为 java.time.LocalDate
. 但我的 XmlAdapter
无效 . 为什么?
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class LocalDateAdapter extends XmlAdapter<String, LocalDate> {
@Override
public LocalDate unmarshal(String v) throws Exception {
return LocalDate.parse(v, DateTimeFormatter.ISO_LOCAL_DATE);
}
@Override
public String marshal(LocalDate v) throws Exception {
return DateTimeFormatter.ISO_LOCAL_DATE.format(date);
}
}
@RestController
public class MyServlet {
@RequestMapping(value = "/", method = RequestMethod.GET)
private String test(RestParams p) {
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RestParams {
@Valid
@NotNull
@XmlElement(required = true, nillable = false)
@XmlJavaTypeAdapter(value = LocalDateAdapter.class)
private LocalDate thedate;
}
结果:
'thedate':无法将[java.lang.String]类型的属性值转换为属性'thedate'的必需类型[java.time.LocalDate];嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[@javax.validation.Valid @javax.validation.constraints.NotNull @javax.xml.bind.annotation .XmlElement @ javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter java.time.LocalDate] for value'2016-08-08';嵌套异常是java.time.format.DateTimeParseException:无法在索引2处解析文本“2016-08-08”
1 回答
我不知道为什么它不起作用,但我用 spring 注释解决了它: