Overview of XML and JSON Generation From Java Object

Introduction

 
This article provides you with a brief view of generating XML and JSON from the Java object. Have you ever thought of any situation where you previously generated an XML file and due to some change your architect or manager told you to convert the Java object to JSON? This is not a new thing since it happens very frequently in organizations. If you need to change your object model to generate JSON then you are a very bad developer since it will create more complexity and your product becomes unstable. What happens when some of your customers want an object in XML format and other customers want the object in JSON format? Really it seems to be a critical issue from the viewpoint of development. In this article, I will show how you can write or define your object model only once but you can generate XML or JSON as and when required. This article provides you with an exposure of JAXB and the Jackson API to do that.
  

Technicalities

 
Let us decide the topic into the following categories that will be helpful to learn.
  • Java Object to XML using JAXB
  • Java Object to JSON using Jackson
  • Existing Java Object that supports XML to JSON

Java Object to XML using JAXB

 
Converting a Java object to XML using JAXB is not a new thing. As you know, the JAXB API is a part of JDK 6. So you can define your POJO and provide some annotations to generate XML from a Java object. Here we will learn the two subjects, generating XML from a Java object and reading XML and converting it back to a Java object. Let us see the structure of an object with JAXB annotations.
  1. import java.util.List;    
  2. import javax.xml.bind.annotation.XmlAccessType;    
  3. import javax.xml.bind.annotation.XmlAccessorType;    
  4. import javax.xml.bind.annotation.XmlElement;    
  5. import javax.xml.bind.annotation.XmlRootElement;    
  6. @XmlRootElement(name = "Employees"@XmlAccessorType(XmlAccessType.FIELD)    
  7. Public Class Employees     
  8. {    
  9.  @XmlElement(name = "Emp"private List < Emp > emp;    
  10.  public List < Emp > getEmp()     
  11.  {    
  12.   return emp;    
  13.  }    
  14.  public void setEmp(List < Emp > emp)     
  15.  {    
  16.   this.emp = emp;    
  17.  }    
  18. }    
The code above is just an outline that will be used to generate XML and convert XML to a Java object.
 

From POJO to XML

 
The following code generates XML from a POJO class.  
  1. JAXBContext jctx = JAXBContext.newInstance(Org.class);  
  2. Marshaller marshaller = jctx.createMarshaller();  
  3. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  4. marshaller.marshal(org, System.out);  
The code above is just a snippet to convert an object to XML. The code above will display the XML contents in the console of your Java editor.
 

To POJO from XML

  
The following code snippet reads the XML contents and converts it back to a Java object.
  1. JAXBContext jctx = JAXBContext.newInstance(Org.class);  
  2. Unmarshaller unmarshaller = jctx.createUnmarshaller();  
  3. Org org = (Org)unmarshaller.unmarshal( new File("xml/text1.xml"));  
  4. System.out.println("Org Id - "+org.getId());  
All the code above however looks very simple to use XML from/to a Java object. There are many other APIs that can serialize a Java object to XML. This is out of our discussion. We will consider that as being provided in the JDK.
 
Now let us learn how to generate JSON from a Java object.
 

Java Object to JSON using Jackson 

 
In this section, we learn about the Jackson API to generate JSON from a Java object. There are other APIs like GSON that does the same thing, but Jackson provides some more flexibility while generating JSON from a Java object. Here we will learn the two subjects again, generating JSON from a Java object and reading JSON and converting back to a Java object. Let us see the structure of an object.
  1. public class Account    
  2. {    
  3.  private String actNo;    
  4.  private String actType;    
  5.  public String getActNo()     
  6.  {    
  7.   return actNo;    
  8.  }    
  9.  public void setActNo(String actNo)     
  10.  {    
  11.   this.actNo = actNo;    
  12.  }    
  13.  public String getActType()    
  14.  {    
  15.   return actType;    
  16.  }    
  17.  public void setActType(String actType)    
  18.  {    
  19.   this.actType = actType;    
  20.  }    
  21. }       
Jackson also provides annotations to generate the JSON with custom fields. Sometimes it is required to generate the JSON contents with all the field names in upper or lower case or based upon the existing system. Let us see the code snippet with Jackson annotations.
  1. import org.codehaus.jackson.annotate.JsonProperty;    
  2. public class Person     
  3. {    
  4.  @JsonProperty(value = "Name")    
  5.  private String name;    
  6.  @JsonProperty(value = "Id")    
  7.  private String id;    
  8.  @JsonProperty(value = "Address")    
  9.  private Address adrs;    
  10. }     

From POJO to JSON

 
The following code snippet is used for both the cases defined above to generate JSON contents.
  1. ObjectMapper mapper = new ObjectMapper();    
  2. System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(customer));     

From JSON to POJO

 
The following code snippet is used to obtain an object from JSON string contents.
  1. ObjectMapper mapper = new ObjectMapper();  
  2. Employee emp = mapper.readValue(jsonStr, Employee.class);   

Existing Java Object that supported for XML to JSON

  
Jackson has a powerful feature that it can convert to JSON from a Java object with JAXB annotations. It really isn't a good feature. As I said in the introduction there are certain situations where you need to convert your object into XML for some customers and JSON for other customers. This is the critical situation where you need to use the power of Jackson. I provide the small code snippet below that supports JAXB annotations in POJO.
 
The following code converts from a Java object to JSON with the support for JAXB annotations.
  1. ObjectMapper mapper = new ObjectMapper();  
  2. AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();  
  3. // make deserializer use JAXB annotations (only)  
  4. mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);  
  5. // make serializer use JAXB annotations (only)  
  6. mapper.getSerializationConfig().setAnnotationIntrospector(introspector);  
  7. jsonStr = mapper.defaultPrettyPrintingWriter().writeValueAsString(emp);  
  8. System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(emp));    
The following code converts from JSON to Java object with the support for JAXB annotations.
  1. ObjectMapper mapper = new ObjectMapper();  
  2. AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();  
  3. mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);  
  4. mapper.getSerializationConfig().setAnnotationIntrospector(introspector);  
  5. Employee emp = mapper.readValue(jsonStr, Employee.class);   

Configuration

  
To have a clear understanding and usage of the preceding concept, download the source code from dropbox at "https://www.dropbox.com/s/ok1nymirqdnara6/xml-json.zip".  Configure the project in the Eclipse editor.
 
As a part of Jackson, the following jar files are used.
  • jackson-core-asl-1.9.12.jar
  • jackson-mapper-asl-1.9.12.jar
  • jackson-xc-1.9.12.jar 
You can download all the relevant jar files from the mvnrespository.com site.
 
Refer to the following classes used in JSON generation using JSON:
  • Account.java
  • Address.java
  • Customer.java
  • Employee.java
  • Person.java
  • Project.java
Refer to the following classes used in XML generation using JAXB:
  • Address.java
  • Desc.java
  • Emp.java
  • Employees.java
  • Org.java
  • FileUtil.java
Refer to the following classes for various types of uses:
  • CreditCardImpl.java
  • DebitCardImpl.java
  • EmailException.java
  • EmailException1.java
Refer to the following classes as testharnesses:
  • TestJsonWithJAXB.java
  • TestJsonWithPojo.java
  • TestWithJsonProperty.java
  • TestXmlDataRetriever.java
  • TestXmlGenerator.java

Conclusion

  
I hope you have enjoyed my small article about the use of XML and JSON from a Java object. Download the complete project and go through the source code to understand the concept and its usage. Based on the complexity and design, you can decide whether to use this concept. 


Similar Articles