Java HTML / XML How to - Change programmatically the default JAXB date serialization








Question

We would like to know how to change programmatically the default JAXB date serialization.

Answer

import java.text.SimpleDateFormat;
import java.util.Date;
/*www .  java 2 s .co  m*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name = "event")
public class Main {

  private Date date;
  private String description;

  @XmlJavaTypeAdapter(DateFormatterAdapter.class)
  public Date getDate() {
    return date;
  }

  public void setDate(final Date date) {
    this.date = date;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(final String description) {
    this.description = description;
  }

  private static class DateFormatterAdapter extends XmlAdapter<String, Date> {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat(
        "dd_mm_yyyy");

    @Override
    public Date unmarshal(final String v) throws Exception {
      return dateFormat.parse(v);
    }

    @Override
    public String marshal(final Date v) throws Exception {
      return dateFormat.format(v);
    }
  }

  public static void main(final String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Main.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Main event = new Main();
    event.setDate(new Date());
    event.setDescription("im rick james");

    marshaller.marshal(event, System.out);
  }
}