31 August 2018

JAXB custom conversion using @XmlJavaTypeAdapter

To provide your own conversion implementation of a JAXB property, annotate the property in your JAXB class with javax.xml.bind.annotation.adapters.@XmlJavaTypeAdapter:

    @XmlJavaTypeAdapter(MyAdapter.class)
   
public void setFrom(LocalDate from) {
       
this.from = from;
    }

 
Then write your Adapter marshalling your LocalDate attribute to an XML value String and unmarshalling it:

    public class MyDateAdapter extends XmlAdapter<String, LocalDate> {
   
public LocalDate unmarshal(String myString) throws Exception {
     
return LocalDate.parse(myString);
    }

   
public String marshal(LocalDate myDate) throws Exception {
     
return myDate.toString();
    }

  }

No comments:

Post a Comment