Unmarshalling LocalDate/LocalDateTime with MOXy

后端 未结 1 1820
孤街浪徒
孤街浪徒 2021-01-26 18:00

How can I get MOXy to unmarshal JSON into LocalDate and LocalDateTime?

I\'ve got an @GET method which produces a sample instance w

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 18:58

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

    public class LocalDateTimeAdapter extends XmlAdapter{
    
      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.

    0 讨论(0)
提交回复
热议问题