Conversion of POJO to JSON and JSON to POJO
In the previous post I explained
that how to convert POJO to XML and XML to POJO? Now with this post I am going
to explain about how to convert POJO to JSON and JSON to POJO? At first, we
will look into what is JSON?
JSON stands for JavaScript Object Notation.
- JSON format is a text format and it is completely language independent.
- It is having similar feature than XML.
- It can also be used for storing and exchanging text information.
- JSON format is providing easier and faster way to parse the content.
- It is a lightweight text-data interchange format.
- As JSON is self-describing format so it is very easy to understand.
- JavaScript syntax is used for describing data objects by JSON.
- JSON is following a hierarchical structure means it is containing values within values.
- The media type for JSON is application/JSON and the file extension used for JSON is .json.
- This format (JSON) is also used for serializing and transmitting structured data over a network connection.
- It is performing as an alternative to XML.
Douglas Crockford, An American computer programmer and entrepreneur is the person who has originally specified and popularized the JSON format.
JSON
Format sample data:-
{
"employee": [
{
"id": "1",
"name": "GAURAV",
"email": "gaurav@yahoo.co.in"
},
{
"id": "2",
"name": "Aryan",
"email": "Aryan@gmail.com"
},
{
"id": "7",
"name": "Madhu",
"email": "madhu@sify.com"
}
],
"recCount": "3"
}
Description of above
sample:-
About Keys and Values in JSON data
format:-
- Keys and Values are two primary parts that make up JSON data.
- Key: A key is always a string enclosed in “” (quotation marks).
- Value: A value can be a string or integer or Boolean or array or an object.
- Key-Value Pair: It follows a specific syntax. Key is separated with Value by a colon and these pairs are separated by comma with others.
Types of values in JSON format data consists of the below basic elements:
- Objects: Objects starts and ends with curly braces ({}).
- Object Members: Members consist of strings and values, separated by colon (:). Members are separated by commas.
- Strings: Strings are surrounded by “” (double quotes) and contain Unicode characters or (\) common backslash escapes.
- Values: A value can be a string or a number or an object or an array or Boolean true or false or null (empty).
- Arrays: Arrays starts and ends with braces and contain values. Values are separated by commas.
Example:- POJO to JSON and JSON to POJO conversion
In this example, I am retrieving the
data from a DB table and generating the retrieved table data as Java object and converting it as JSON data and then
reading the JSON data and converting back it to java object.
System Requirement for this sample
application:-
- The Extra jar needed for the execution of this program is jackson-all-1.8.3.jar.
- JDK 1.6 or above.
- Eclipse Helios or above
- Hibernate API jars
- MySQL database and corresponding jar.
For Table structure and Insert Scripts, Required Jars and Steps to create this demo example
Please follow the below given link:-
Only change is in the client program file.
Converter.java
package
com.gaurav.jaxbimplementation;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Converter {
private static EmpDS employeeDS = new EmpDS();
private String pojo2Json(Object obj) throws JAXBException,
JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(obj);
return jsonString;
}
private Object json2Pojo(String jsonString) throws JAXBException,
JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
Employees empBeanList = objectMapper.readValue(jsonString,
Employees.class);
Object object = (Object) empBeanList;
return object;
}
private String pojo2Xml(Object object, JAXBContext context)
throws JAXBException {
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(object, writer);
String xmlStringData = writer.toString();
return xmlStringData;
}
private Employees xml2Pojo(String xmlStringData, JAXBContext context)
throws JAXBException {
StringReader reader = new StringReader(xmlStringData);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employees employee = (Employees) unmarshaller.unmarshal(reader);
return employee;
}
@SuppressWarnings("unchecked")
public static void main(String args[]) {
JAXBContext context = null;
Converter converter = new Converter();
List<Employee> employeesList = employeeDS.retrieveEmployee();
Employee empBean = null;
Employees employees = new Employees();
try {
int counter = 0;
for (Employee bean : employeesList) {
empBean = new Employee();
empBean.setId(bean.getId());
empBean.setName(bean.getName());
empBean.setEmail(bean.getEmail());
counter++;
employees.setRecCount(counter);
employees.getEmployee().add(empBean);
}
} catch (Exception e) {
e.printStackTrace();
}
String jsonData = null;
try {
context = JAXBContext.newInstance(Employees.class);
String xmlStringData = converter.pojo2Xml(employees,
context);
System.out
.println("\nPOJO to XML conversion(Marshal) demonstration in Java");
System.out.println(xmlStringData);
employees = converter.xml2Pojo(xmlStringData,
context);
System.out
.println("\nXML to POJO conversion(UnMarshal) demonstration in Java");
System.out.println(employees);
jsonData = converter.pojo2Json(employees);
System.out
.println("\nPOJO to JSON conversion demonstration in Java using jackson");
System.out.println(jsonData);
System.out
.println("\nJSON to POJO conversion demonstration in Java using jackson");
Object obj = converter.json2Pojo(jsonData);
employees = (Employees) obj;
System.out.println(employees);
} catch (JsonParseException jpe) {
Logger.getLogger(JsonParseException.class.getName()).log(
Level.SEVERE, null, jpe);
} catch (JsonMappingException e1) {
e1.printStackTrace();
} catch (JAXBException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Converter {
private static EmpDS employeeDS = new EmpDS();
private String pojo2Json(Object obj) throws JAXBException,
JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(obj);
return jsonString;
}
private Object json2Pojo(String jsonString) throws JAXBException,
JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
Employees empBeanList = objectMapper.readValue(jsonString,
Employees.class);
Object object = (Object) empBeanList;
return object;
}
private String pojo2Xml(Object object, JAXBContext context)
throws JAXBException {
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(object, writer);
String xmlStringData = writer.toString();
return xmlStringData;
}
private Employees xml2Pojo(String xmlStringData, JAXBContext context)
throws JAXBException {
StringReader reader = new StringReader(xmlStringData);
Unmarshaller unmarshaller = context.createUnmarshaller();
Employees employee = (Employees) unmarshaller.unmarshal(reader);
return employee;
}
@SuppressWarnings("unchecked")
public static void main(String args[]) {
JAXBContext context = null;
Converter converter = new Converter();
List<Employee> employeesList = employeeDS.retrieveEmployee();
Employee empBean = null;
Employees employees = new Employees();
try {
int counter = 0;
for (Employee bean : employeesList) {
empBean = new Employee();
empBean.setId(bean.getId());
empBean.setName(bean.getName());
empBean.setEmail(bean.getEmail());
counter++;
employees.setRecCount(counter);
employees.getEmployee().add(empBean);
}
} catch (Exception e) {
e.printStackTrace();
}
String jsonData = null;
try {
context = JAXBContext.newInstance(Employees.class);
String xmlStringData = converter.pojo2Xml(employees,
context);
System.out
.println("\nPOJO to XML conversion(Marshal) demonstration in Java");
System.out.println(xmlStringData);
employees = converter.xml2Pojo(xmlStringData,
context);
System.out
.println("\nXML to POJO conversion(UnMarshal) demonstration in Java");
System.out.println(employees);
jsonData = converter.pojo2Json(employees);
System.out
.println("\nPOJO to JSON conversion demonstration in Java using jackson");
System.out.println(jsonData);
System.out
.println("\nJSON to POJO conversion demonstration in Java using jackson");
Object obj = converter.json2Pojo(jsonData);
employees = (Employees) obj;
System.out.println(employees);
} catch (JsonParseException jpe) {
Logger.getLogger(JsonParseException.class.getName()).log(
Level.SEVERE, null, jpe);
} catch (JsonMappingException e1) {
e1.printStackTrace();
} catch (JAXBException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Result:-
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select employee0_.id as
id0_, employee0_.name as name0_, employee0_.email as email0_ from employee employee0_
POJO to XML conversion(Marshal) demonstration in Java
POJO to XML conversion(Marshal) demonstration in Java
<?xml version="1.0"
encoding="UTF-8" standalone="yes"?>
<employees>
<employee>
<id>1</id>
<name>GAURAV</name>
<email>gaurav@yahoo.co.in</email>
</employee>
<employee>
<id>2</id>
<name>Aryan</name>
<email>Aryan@gmail.com</email>
</employee>
<employee>
<id>7</id>
<name>Madhu</name>
<email>madhu@sify.com</email>
</employee>
<recCount>3</recCount>
</employees>
XML to POJO conversion(UnMarshal) demonstration in Java
<employees>
<employee>
<id>1</id>
<name>GAURAV</name>
<email>gaurav@yahoo.co.in</email>
</employee>
<employee>
<id>2</id>
<name>Aryan</name>
<email>Aryan@gmail.com</email>
</employee>
<employee>
<id>7</id>
<name>Madhu</name>
<email>madhu@sify.com</email>
</employee>
<recCount>3</recCount>
</employees>
XML to POJO conversion(UnMarshal) demonstration in Java
RecordCount: 3
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]
POJO to JSON conversion demonstration in Java using jackson
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]
POJO to JSON conversion demonstration in Java using jackson
{"employee":[{"email":"gaurav@yahoo.co.in","name":"GAURAV","id":1},{"email":"Aryan@gmail.com","name":"Aryan","id":2},{"email":"madhu@sify.com","name":"Madhu","id":7}],"recCount":3}
JSON to POJO conversion demonstration in Java using jackson
JSON to POJO conversion demonstration in Java using jackson
RecordCount: 3
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]
employees:
[Employee [id=1, name=GAURAV, email=gaurav@yahoo.co.in], Employee [id=2, name=Aryan, email=Aryan@gmail.com], Employee [id=7, name=Madhu, email=madhu@sify.com]]
There is a far simpler way to convert JSON to POJO and vice versa using GSON.
ReplyDeleteCheck this link for a detailed explanation.
http://atechiediary.blogspot.in/2013/06/javajsextjs-convert-serialize-java.html