Tuesday, 13 June 2017

How to Convert JSON to Java Object and Java Object to JSON?

In below java codes consider both the cases from JSON to Java Object and Java Object to JSON by ObjectMapper by Jacson API’s

I have given generic method for both the cases as convertJavaObjectToJSON and convertJSONToJavaObject.

Pre-Requisite : Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.8.5</version>
</dependency>

JAVA and JSON Conversion Example:


Below is complete example for conversion of both the cases.

ObjectMapper.readValue():Convert JSON String to Java Object

ObjectMapper.writeValue(): Convert JAVA Object to JSON

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class JsonAndJavaObjectConversion {

    public static void main(String[] args) {
        System.out.println("=================Convert Student Java Object to JSON==============");
        // convert Object to json string
        Student student = sampleStudentObject();

        String studentStr = convertJavaObjectToJSON(student);
        System.out.println("Student JSON Data \n" + studentStr);
        System.out.println("=================Convert JSON DATA  to Student JAVA Object==============");
        Object object = convertJSONToJavaObject(studentStr, Student.class);
        if (object != null && object instanceof Student) {
            System.out.println("Student Object\n" + (Student) object);
        }

    }
    //Generic Method to convert JSON object to Java Object
    public static Object convertJSONToJavaObject(String strJsonData, Class className) {
        try {
            // ObjectMapper new instance
            ObjectMapper objectMapper = new ObjectMapper();
            // //convert json data from file text to object
            return objectMapper.readValue(strJsonData, className);
        } catch (JsonMappingException ex) {
            ex.printStackTrace();
        } catch (JsonGenerationException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
    //Generic Method to convert Java object to JSON
    public static String convertJavaObjectToJSON(Object javaObject) {
        StringWriter jsonStr = null;
        try {

            // ObjectMapper new instance
            ObjectMapper objectMapper = new ObjectMapper();
            // configure Object mapper for pretty print
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

            // writing to console, can write to any output stream such as file
            jsonStr = new StringWriter();
            objectMapper.writeValue(jsonStr, javaObject);

        } catch (JsonMappingException ex) {
            ex.printStackTrace();
        } catch (JsonGenerationException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return jsonStr.toString();
    }

    public static Student sampleStudentObject() {

        Student student = new Student();
        student.setRollNumber(11);
        student.setFirstName("Saurabh");
        student.setLastName("Gupta");
        student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

        Address add = new Address();
        add.setAddressLine("Lake Union Hill Way");
        add.setCity("Atlanta");
        add.setState("GA");
        add.setZipCode(50005);
        student.setAddress(add);

        List<String> cities = new ArrayList<String>();
        cities.add("Dallas");
        cities.add("San Antonio");
        cities.add("Irving");
        student.setCities(cities);

        Map<String, String> props = new HashMap<String, String>();
        props.put("age", "34 years");
        props.put("interst", "Math");
        props.put("play", "Badminton");

        student.setProperties(props);

        return student;
    }

}

Model Classes :


package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Student {
    private int rollNumber;
    private String firstName;
    private String lastName;
    private boolean permanent;
    private Address address;
    private long[] phoneNumbers;
    private List<String> cities;
    private Map<String, String> properties;
    @Override
    public String toString()
    {
        StringBuffer sb=new StringBuffer();
        sb.append("==============Student Information================\n");
        sb.append("rollNumber=").append(rollNumber).append("\n");
        sb.append("firstName=").append(firstName).append("\n");
        sb.append("lastName=").append(lastName).append("\n");
        sb.append("permanent=").append(permanent).append("\n");
        sb.append("adress=").append(address).append("\n");
        sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
        sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
        sb.append("properties=").append(properties).append("\n");
        return sb.toString();
    }
    public int getRollNumber() {
        return rollNumber;
    }
    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public boolean isPermanent() {
        return permanent;
    }
    public void setPermanent(boolean permanent) {
        this.permanent = permanent;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public long[] getPhoneNumbers() {
        return phoneNumbers;
    }
    public void setPhoneNumbers(long[] phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
    public List<String> getCities() {
        return cities;
    }
    public void setCities(List<String> cities) {
        this.cities = cities;
    }
    public Map<String, String> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, String> properties) {
        this.properties = properties;
    }

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
    StringBuffer sb=new StringBuffer();
    sb.append("AddressLine=").append(addressLine).append("\n");
    sb.append("city=").append(city).append("\n");
    sb.append("state=").append(state).append("\n");
    sb.append("zipCode=").append(zipCode).append("\n");
    return sb.toString();
}
public String getAddressLine() {
    return addressLine;
}
public void setAddressLine(String addressLine) {
    this.addressLine = addressLine;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getState() {
    return state;
}
public void setState(String state) {
    this.state = state;
}
public int getZipCode() {
    return zipCode;
}
public void setZipCode(int zipCode) {
    this.zipCode = zipCode;
}
}

Output:


=================Convert Student Java Object to JSON==============
Student JSON Data
{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "state" : "GA",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
}
=================Convert JSON DATA  to Student JAVA Object==============
Student Object
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=GA
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}