Overview of XML and JSON Generation From Java Object

Introduction

This article provides you a brief view of generating XML and JSON from the Java object. Have you ever thought of any situation where you previously generated a 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 an exposure of JAXB and the Jackson API to do that.

Technicalities

Let us devide 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.

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement( name="Employees")

@XmlAccessorType( XmlAccessType.FIELD )

Public Class Employees

{

@XmlElement(name="Emp") private List<Emp> emp;

public List<Emp> getEmp() {

return emp;

}

public void setEmp(List<Emp> emp) {

this.emp = emp;

}

}


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.
  

  

JAXBContext jctx = JAXBContext.newInstance(Org.class);

Marshaller marshaller = jctx.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

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 convets it back to a Java object.
 

JAXBContext jctx = JAXBContext.newInstance(Org.class);

Unmarshaller unmarshaller = jctx.createUnmarshaller();

Org org = (Org)unmarshaller.unmarshal( new File("xml/text1.xml"));

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 .
 

public class Account {

private String actNo;

private String actType;

public String getActNo() {

return actNo;

}

public void setActNo(String actNo) {

this.actNo = actNo;

}

public String getActType() {

return actType;

}

public void setActType(String actType) {

this.actType = actType;

}

}

Jackson also provides annotations to generate the JSON with custom fields. Sometime 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.
 

import org.codehaus.jackson.annotate.JsonProperty;

public class Person {

@JsonProperty(value = "Name")

private String name;

@JsonProperty(value = "Id")

private String id;

@JsonProperty(value = "Address")

private Address adrs;

//Getter and Setter Methods

}


From POJO to JSON

The following code snippet is used for both the cases defined above to generate JSON contents.
 

ObjectMapper mapper = new ObjectMapper();

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(customer));

 

From JSON to POJO

The following code snippet is used to obtain object from json string contents.

ObjectMapper mapper = new ObjectMapper();

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 supoort for JAXB annotations.
 

ObjectMapper mapper = new ObjectMapper();

AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();

// make deserializer use JAXB annotations (only)

mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);

// make serializer use JAXB annotations (only)

mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

jsonStr = mapper.defaultPrettyPrintingWriter().writeValueAsString(emp);

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(emp));


The following code converts from JSON to Java object with the supoort for JAXB annotations.
 

ObjectMapper mapper = new ObjectMapper();

AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();

mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);

mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

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 upon the complexity and design, you can decide whether to use this concept.

Up Next
    Ebook Download
    View all
    Learn
    View all