Saturday, 20 August 2016

JAXB: Marshaling data using generated ObjectFactory class

This is continuation to my previous post, You can get all the following model classes from previous post.

Address.java
Details.java
Employee.java
Employees.java
Project.java
ObjectFactory.java

Marshalling is the process of converting java object to XML document.


Step1: Get JAXBContext instance by using ObjectFactory class.
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

Step 2: Get Marshaller instance using jaxbContext object created in step 1.
Marshaller marshaller = jaxbContext.createMarshaller();

Step 3: Use marshal method to convert java object to XML.

Test.java
package generated;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Test {

 public static Employee getEmployee() {

  Employee emp1 = new Employee();
  emp1.setDescendants(2);
  emp1.setDescription("from India");

  Details details = new Details();
  details.setAge(27);
  details.setFirstname("Hari Krishna");
  details.setLastname("Gurram");
  details.setMarried("No");
  details.setMiddlename("");
  details.setSalary(new BigDecimal("1234"));
  details.setSex("male");

  emp1.setDetails(details);

  return emp1;

 }

 public static void main(String args[]) throws JAXBException {
  JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

  Marshaller marshaller = jaxbContext.createMarshaller();
  Employees employees = new Employees();

  Employee emp = getEmployee();

  employees.getEmployee().add(emp);

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


Run above application, you can able to see following xml.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
 <employee>
  <description>from India</description>
  <taxExemption>0.0</taxExemption>
  <descendants>2</descendants>
  <satifiedWithWork>false</satifiedWithWork>
  <details>
   <firstname>Hari Krishna</firstname>
   <middlename></middlename>
   <lastname>Gurram</lastname>
   <age>27</age>
   <salary>1234</salary>
   <married>No</married>
   <sex>male</sex>
  </details>
 </employee>
</employees>




Previous                                                 Next                                                 Home

No comments:

Post a Comment