How to convert JSON to Java Object and vice versa using Jackson

In this tutorial, we will see how to convert JSON from/to java object  using Jackson. JSON is one of the preferred way of data exchange between applications through webservice. In many applications it is required to map JSON to java object and vice versa so that the application can make use of it. In this example, we will do the following

a) Convert JSON to Java Object

b) Convert Java Object to JSON

c) Java List of Objects to JSON

d) JSON List of Objects to Java List of Objects

Required Jackson Libraries:

jackson-databind-2.6.1.jar

jackson-annotations-2.6.0.jar

jackson-core-2.6.1.jar

Jackson Maven Dependency:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.javaonline.JavaObjectToJSON</groupId>
  <artifactId>JavaObjectToJSON</artifactId>
  <version>0.0.1-SNAPSHOT</version>
 
  
   <dependencies>
   <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.6.1</version>
	</dependency>
  </dependencies>
</project>
Creating Java Object (POJO):

In this example, we will create an User class having the properties of userId, name, email, mobile and address. address is a class type having the fields of address1, address2, city, pincode, state. User and Address class is given below.

//User class


class User {

	private String userId;
	private String name;
	private String email;
	private String mobile;
	private Address address;

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

}

//Address class

class Address {
	private String address1;
	private String address2;
	private String city;
	private String pincode;
	private String state;

	public String getAddress1() {
		return address1;
	}

	public void setAddress1(String address1) {
		this.address1 = address1;
	}

	public String getAddress2() {
		return address2;
	}

	public void setAddress2(String address2) {
		this.address2 = address2;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPincode() {
		return pincode;
	}

	public void setPincode(String pincode) {
		this.pincode = pincode;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

}

The Complete Java Code  is given below

Java Code for converting JSON from/to Java Object:

 


package net.javaonline;

import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaObjectToJSON {

	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		
	
		
//Java Object (user1) creation		
		User user1 = new User();
		user1.setUserId("guest1");
		user1.setName("ABC");
		user1.setEmail("abc@xyz.com");
		user1.setMobile("9999999999");

			Address address = new Address();
			address.setAddress1("Address1");
			address.setAddress2("Address2");
			address.setCity("New Delhi");
			address.setPincode("110001");
			address.setState("Delhi");

		user1.setAddress(address);

		
//Create mapper
		ObjectMapper mapper = new ObjectMapper();

		
		
		
		// Java Object to JSON
		String json1 = JavaObjectToJSON(user1, mapper);

		System.out.println("JSON String " + json1);

		
		//Creating user list to have more users
		
		  ArrayList<User> userList = new ArrayList<User>(); 
		  
		  //user1 object  is added to list 
		  userList.add(user1);
		  
		  User user2 = new User(); 
		  user2.setUserId("guest2");
		  user2.setName("XYZ"); 
		  user2.setEmail("xyz@test.com");
		  user2.setMobile("1111111111");
			Address address1 = new Address();
			address1.setAddress1("Address1");
			address1.setAddress2("Address2");
			address1.setCity("Chennai");
			address1.setPincode("628001");
			address1.setState("TN");

		 user2.setAddress(address1);
		  
		  
		 
		  userList.add(user1);
		 

		// Array of Java Objects to JSON

		 String json2 = JavaListObjectsToJSON(userList, mapper);

		 System.out.println("JSON Array List String " + json2);

		  String userJson =  "{\"userId\":\"guest3\",\"name\":\"Kumar\",\"email\":\"guest3@xyz.com\",\"mobile\":\"9999999999\",\"address\":{\"address1\":\"Address1\",\"address2\":\"Address2\",\"city\":\"Bangalore\",\"pincode\":\"560001\",\"state\":\"Karnataka\"}}" ;
		  
		  // JSON to Java Object (user3)
		  
		  User user3 = JSONToJavaObject(userJson, mapper);
		  
		  //printing user details
		  
		  System.out.println("User Id: " + user3.getUserId());
		  System.out.println("Name: " + user3.getName());
		  System.out.println("e-Mail: " + user3.getEmail());
		  System.out.println("Mobile: " + user3.getMobile());
		  System.out.println("Address: " + user3.getAddress().getAddress1() +", " + user3.getAddress().getAddress2() +", "+user3.getAddress().getCity()+", "+user3.getAddress().getPincode()+", "+user2.getAddress().getState());
		  
		  
		  


		  //JSON Array List
		  
		  String userJsonArray="["
		  		+ "{"
		  		+ "\"userId\":\"guest1\",\"name\":\"ABC\",\"email\":\"abc@xyz.com\",\"mobile\":\"9999999999\",\"address\":{\"address1\":\"Address1\",\"address2\":\"Address2\",\"city\":\"New Delhi\",\"pincode\":\"110001\",\"state\":\"Delhi\"}"
		  		+ "},"
		  		+ "{"
		  		+ "\"userId\":\"guest2\",\"name\":\"XYZ\",\"email\":\"xyz@test.com\",\"mobile\":\"1111111111\",\"address\":{\"address1\":\"Address1\",\"address2\":\"Address2\",\"city\":\"Chennai\",\"pincode\":\"628001\",\"state\":\"TN\"}"
		  		+ "}"
		  		+ "]";
	
		  
		  //Json Array List to List of Java Objects
		 
		  List<User> userList1 = JSONListToJavaList(userJsonArray, mapper);
		  
		  
		  //Printing all user objects from the list  
		  
		  for (User  user4 : userList1)
		  {
			  System.out.println("User Id: " + user4.getUserId());
			  System.out.println("Name: " + user4.getName());
			  System.out.println("e-Mail: " + user4.getEmail());
			  System.out.println("Mobile: " + user4.getMobile());
			  System.out.println("Address: " + user4.getAddress().getAddress1() +", " + user4.getAddress().getAddress2() +", "+user4.getAddress().getCity()+", "+user4.getAddress().getPincode()+", "+user4.getAddress().getState());
		  }
		  
		  
	}
	
	
	

	// Method to convert JSON to Java Object
	
	public static User JSONToJavaObject(String userJson, ObjectMapper mapper) throws JsonParseException, JsonMappingException, IOException {

		User user = null;

			user = mapper.readValue(userJson, User.class);

		return user;

	}
	
	
	//Method to convert Java Object to JSON

	public static String JavaObjectToJSON(User user, ObjectMapper mapper) throws JsonGenerationException, JsonMappingException, IOException {

		String json = "";
			mapper.writeValue(new File("c:\\temp\\user.json"), user);
			json = mapper.writeValueAsString(user);

		return json;

	}

	
	//Method to convert Java List of Objects to JSON
	
	public static String JavaListObjectsToJSON(ArrayList<User> userList, ObjectMapper mapper) throws JsonGenerationException, JsonMappingException, IOException {

		String json = "";
			mapper.writeValue(new File("c:\\temp\\user.json"), userList);

			json = mapper.writeValueAsString(userList);

		return json;

	}
	
	
	//Method to convert JSON List to Java List
	
	
	public static List<User> JSONListToJavaList(String jsonUserArray, ObjectMapper mapper) throws JsonParseException, JsonMappingException, IOException
	{
		
		List<User> list = mapper.readValue(
				jsonUserArray, mapper.getTypeFactory().constructCollectionType(List.class, User.class));
		
		return list;
		
	}

}


//User class

class User {

	private String userId;
	private String name;
	private String email;
	private String mobile;
	private Address address;

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

}

//Address class

class Address {
	private String address1;
	private String address2;
	private String city;
	private String pincode;
	private String state;

	public String getAddress1() {
		return address1;
	}

	public void setAddress1(String address1) {
		this.address1 = address1;
	}

	public String getAddress2() {
		return address2;
	}

	public void setAddress2(String address2) {
		this.address2 = address2;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPincode() {
		return pincode;
	}

	public void setPincode(String pincode) {
		this.pincode = pincode;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

}

//Paste User and Address class here

//User class
//....
//.....
//Address Class
//....
//.....


Note : Make sure temp folder is created under c: drive to create JSON file.
Output:

json from to java object

 

 

You may also like

Leave a Reply

Be the First to Comment!