我有这样的模型和字段:
@Element(name = "TIMESTAMP")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime date;
我收到的回复:
<TIMESTAMP>2016-05-04T13:13:42.000</TIMESTAMP>
但是在将 xml 解析为模型期间出现错误:
"message": "org.simpleframework.xml.core.PersistenceException: Constructor not matched for class java.time.LocalDateTime",
我也尝试过:
@Element(name = "TIMESTAMP")
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
private LocalDateTime date;
但这仍然不起作用。任何想法 ?我正在使用 springframework.xml
lib。
最佳答案
问题是默认情况下 simplexml lib 不知道如何序列化/反序列化新的 Java8 日期类型。
为了成功,您需要使用自定义转换器。
示例实体(请参阅特殊的 @Convert 注释)
public class Entity {
@Element(name = "TIMESTAMP")
@Convert(LocalDateTimeConverter.class)
private LocalDateTime date;
// omitted
}
特殊转换器
public class LocalDateTimeConverter implements Converter<LocalDateTime> {
public LocalDateTime read(InputNode node) throws Exception {
String name = node.getValue();
return LocalDateTime.parse(name, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
public void write(OutputNode node, LocalDateTime input) {
String value = input.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
node.setValue(value);
}
}
使用
Strategy strategy = new AnnotationStrategy();
Persister persister = new Persister(strategy);
Entity serializedEntity = persister.read(Entity.class, xmlInputStream);
完整源代码可在 GitHub 上找到
关于java - Spring,将字符串解析为 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37047525/