The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling from POJO to XML can be done to a variety of output targets. 1. Maven Start with adding the latest ‘jakarta‘ dependencies for adding the …
The JAXB Marshaller interface is responsible for governing the process of serializing Java content trees i.e. Java objects to XML data. This marshalling from POJO to XML can be done to a variety of output targets.
Generally, to create a marshaller we can get the Marshaller instance from the JAXBContext. In the following example, we are creating a marshaller instance for the Employee class. It can be used to convert an instance of the Employee class into XML string.
JAXBContext jaxbContext =JAXBContext.newInstance(Employee.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();Employee employeeObj =newEmployee(1,"Lokesh","Gupta",newDepartment(101,"IT"));//Overloaded methods to marshal to different outputs
jaxbMarshaller.marshal(employee,System.out);
jaxbMarshaller.marshal(employee,newFile("output.xml"));
jaxbMarshaller.marshal(employee,newStringWriter());
2.2. Marshal POJO to File
The following code marshals the Employee object and writes the XML into employee.xml file.
OutputStream os =newFileOutputStream("employee.xml");
jaxbMarshaller.marshal( employeeObj, os );
2.3. Marshal POJO to SAX ContentHandler
Assume MyContentHandler is instance of org.xml.sax.ContentHandler. The content handler can be used to customize the XML output during the marshalling process.
All JAXB Providers are required to support the following set of properties. Some providers may support additional properties.
jakarta.encoding – The output encoding to use when marshalling the XML data. The Marshaller will use “UTF-8” by default if this property is not specified.
jakarta.formatted.output – Value can be true or false. Whether or not the Marshaller will format the resulting XML data with line breaks and indentation. Default value is false.
jakarta.schemaLocation – It allows the client application to specify an xsi:schemaLocation attribute in the generated XML data.
jakarta.noNamespaceSchemaLocation – It allows the client application to specify an xsi:noNamespaceSchemaLocation attribute in the generated XML data.
jakarta.fragment – It determines whether or not document-level events will be generated by the Marshaller. Value can be true or false.
4. Marshaller Callback Methods
We can customize the marshalling operation inside JAXB annotated class e.g. Employee.java. We need to define two methods that will listen before and after the marshaller process in that class. In these methods, we can perform actions such as setting extra fields or modifying the value of existing fields.
In the following example, we are defining the methods beforeMarshal() and afterMarshal() that will be invoked by JAXB marshaller before and after the marshalling is done.
importjava.io.Serializable;importjakarta.xml.bind.Marshaller;importjakarta.xml.bind.annotation.XmlAccessType;importjakarta.xml.bind.annotation.XmlAccessorType;importjakarta.xml.bind.annotation.XmlRootElement;@XmlRootElement(name ="employee")@XmlAccessorType(XmlAccessType.PROPERTY)publicclassEmployeeimplementsSerializable{privatestaticfinallong serialVersionUID =1L;privateInteger id;privateString firstName;privateString lastName;privateDepartment department;publicEmployee(){super();}//Setters and Getters@OverridepublicStringtoString(){return"Employee [id="+ id +", firstName="+ firstName +", lastName="+ lastName +", department="+ department +"]";}// Invoked by Marshaller after it has created an instance of this object.booleanbeforeMarshal(Marshaller marshaller){System.out.println("Before Marshaller Callback");returntrue;}// Invoked by Marshaller after it has marshalled all properties of this object.voidafterMarshal(Marshaller marshaller){System.out.println("After Marshaller Callback");}}
5. JAXB Marshalling Example
The following is an example of marshalling an Employee instance to XML String and printing to the console.
importjava.io.StringWriter;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.JAXBException;importjavax.xml.bind.Marshaller;importcom.howtodoinjava.demo.model.Department;importcom.howtodoinjava.demo.model.Employee;publicclassJaxbExample{publicstaticvoidmain(String[] args){Employee employee =newEmployee(1,"Lokesh","Gupta",newDepartment(101,"IT"));jaxbObjectToXML(employee);}privatestaticvoidjaxbObjectToXML(Employee employee){try{JAXBContext jaxbContext =JAXBContext.newInstance(Employee.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);// To format XML//Print XML String to Console
jaxbMarshaller.marshal(employee,System.out);}catch(JAXBException e){
e.printStackTrace();}}}
Program Output.
Before Marshaller Callback
After Marshaller Callback
<?xml version="1.0" encoding="UTF-8"?><employee><department><id>101</id><name>IT</name></department><firstName>Lokesh</firstName><id>1</id><lastName>Gupta</lastName></employee>
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments