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
- 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.
The following code generates XML from a POJO class.
From POJO to XML
- 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.
The following code snippet reads the XML contents and converts it back to a Java object.
To POJO from XML
- 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
- 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. 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.
- 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;
- }
From POJO to JSON
- ObjectMapper mapper = new ObjectMapper();
- 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.
- ObjectMapper mapper = new ObjectMapper();
- Employee emp = mapper.readValue(jsonStr, Employee.class);
Existing Java Object that supported for XML to JSON
- 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 support 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
- jackson-core-asl-1.9.12.jar
- jackson-mapper-asl-1.9.12.jar
- jackson-xc-1.9.12.jar
-
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

Comments
Join the conversation! Your thoughts help the community grow.