java - Spring,将字符串解析为 LocalDateTime

标签 java xml spring

我有这样的模型和字段:

@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/

相关文章:

java - 使用 Java 的 Adob​​e Air Native Process

java - 用java编写一个带有事件处理的简单电话簿代码

java - 尝试使用 GSON 反序列化 JSON 字符串时出现错误

php - 立陶宛字符未正确保存到 MySQL 数据库中

android - 如何在 android 中的 style.xml 文件中设置 CardView 属性

java - 微服务 - 如何使用授权服务器和资源服务器对注册流程进行建模?

spring - 使用 Grail 插件 spring-security-rest 获取 403 错误承载错误 ="insufficient_scope"#3

java - 用于检查前缀和后缀的正则表达式语法

java - eclipse : Element type "Context" must be declared

java - 将 XSLT 放在客户端 Web 应用程序中的何处