Java HTML / XML How to - Handle null in JAXB Marshaller








Question

We would like to know how to handle null in JAXB Marshaller.

Answer

//from  w  w w .  j av  a2s.c  o m
import java.math.BigDecimal;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.datatype.XMLGregorianCalendar;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(PersonTraining.class);

    PersonTraining pt = new PersonTraining();

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(pt, System.out);
  }

  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class PersonTraining {

    @XmlElement(name = "Val1", required = true)
    protected BigDecimal val1;
    @XmlElement(name = "Val2", required = true, nillable = true)
    protected BigDecimal val2;
    @XmlElement(name = "Val3", required = true, nillable = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar val3;

  }
}