Unmarshalling LocalDate/LocalDateTime with MOXy

扶醉桌前 提交于 2019-12-02 08:01:37

According to peeskillet's suggestion I implemented the following adapter class:

public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime>{

  private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

  @Override
  public String marshal(LocalDateTime localDateTime) throws Exception {
    return localDateTime.format(DTF);
  }

  @Override
  public LocalDateTime unmarshal(String string) throws Exception {
    return LocalDateTime.parse(string, DTF);
  }

}

In addition, I created package-info.java in the same package where my classes for MOXy and the adapter (in a subpackage) are located with the following content:

@XmlJavaTypeAdapters({
  @XmlJavaTypeAdapter(type=LocalDateTime.class,
      value=LocalDateTimeAdapter.class)
})
package api;

import java.time.LocalDateTime;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;

import api.adapter.LocalDateTimeAdapter;

Thus, marshalling and unmarshalling works without problems. And with DTF you can specify the format that shall be applied.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!