Generic+JSON+Object+Jackson

Context 

I was doing code review of one of the project which has so many REST call, All the JSON response look like below JSON. Developer who did this, he wrote entire REST calls on each places also having mapping methods after each REST calls. It seems wired to me as I do not like this kind of approach hence I came up with below solution. I introduce a method which do REST call and create object of the POJO class. After that I was able to reduce so many lines of the code and now code is more flexible and extensible.

This is example of create any object of POJO class from JSON using Generic Approach. 

  1. Sample JSON

user.json

{
“user”:{
“userid”:1,
“firstname”:“Shailendra”,
“lastname”:“Soni”,
“gender”:“Male”
}
}

  1. I have created marker interface.
/**
* Marker Interface - Implement on POJO which you need to create Object from JSON
* @author Shailendra Soni
*
*/
public interface JsonPojoParserInt {

}

3. I have created POJO class with having member variables correspoing to user.json

import com.bs.genericjson.convertor.JsonPojoParserInt;

/**
* @author Shailendra Soni
*
*/
public class User implements JsonPojoParserInt {
private int userid;
private String firstname;
private String lastname;
private String gender;

/**
* @return the userid
*/
public int getUserid() {
return userid;
}

/**
* @param userid
* the userid to set
*/
public void setUserid(int userid) {
this.userid = userid;
}

/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}

/**
* @param firstname
* the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}

/**
* @return the lastname
*/
public String getLastname() {
return lastname;
}

/**
* @param lastname
* the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}

/**
* @return the gender
*/
public String getGender() {
return gender;
}

/**
* @param gender
* the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [userid=");
builder.append(userid);
builder.append(", firstname=");
builder.append(firstname);
builder.append(", lastname=");
builder.append(lastname);
builder.append(", gender=");
builder.append(gender);
builder.append("]");
return builder.toString();
}

}

4. Now, I have created main class which responsible to parse JSON and then return object of the POJO with values,

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
* Convert JSON to java object
*
* @author Shailendra Soni
*
*/
public class JsonToObject<T extends JsonPojoParserInt> {

/**
* Generic method for convert JSON response to POJO, make sure POJO should implement {@link JsonPojoParserInt}
*
* @param jsonString
* @param jsonRootNode
* @param classzz
* @return
* @throws JsonGenerationException
* @throws JsonMappingException
* @throws IOException
*/
public T readJSONResponse(String jsonString, String jsonRootNode, Class classzz)
throws JsonGenerationException, JsonMappingException, IOException {

ObjectMapper objMapper = new ObjectMapper();
JsonNode jsonNode = objMapper.readTree(jsonString);
objMapper.configure(MapperFeature.AUTO_DETECT_FIELDS, true);
objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objMapper.readValue(jsonNode.path(jsonRootNode).traverse(), classzz);
}

}

5. Example to convert JSON to POJO object,

import java.io.IOException;

import com.bs.genericjson.convertor.JsonToObject;
import com.bs.genericjson.module.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToObjectExample {
public static void main(String[] args) throws JsonProcessingException, IOException {
ObjectMapper mapper = new ObjectMapper();

String jsonString = mapper.readTree(JsonToObjectExample.class.getClassLoader().getResourceAsStream("user.json")).toString();
System.out.println(jsonString);

JsonToObject jsonToObject = new JsonToObject();
User user = jsonToObject.readJSONResponse(jsonString, "user", User.class);
System.out.println(user);

}
}

6. Output,

JSON Input String :-{"user":{"userid":1,"firstname":"Shailendra","lastname":"Soni","gender":"Male"}}
POJO Object Result :- User [userid=1, firstname=Shailendra, lastname=Soni, gender=Male]

7.Another example

employee.json

{“employee”:{
“employeetype”: “Full Time”,
“dept”: “tech”,
“phoneextn”: 1001,
“user”: {
“userid”: 1,
“firstname”: “Shailendra”,
“lastname”: “Soni”,
“gender”: “Male”
}
}}

8.Below is Emlpoyee class which has member variables corresponding to employee.json


import com.bs.genericjson.convertor.JsonPojoParserInt;

/**
 * @author Shailendra Soni
 *
 */
public class Employee implements JsonPojoParserInt{

    private String employeetype;
    private String dept;
    private int phoneextn;
    private User user;

    /**
     * @return the employeeType
     */
    public String getEmployeetype() {
        return employeetype;
    }

    /**
     * @param employeeType
     *            the employeeType to set
     */
    public void setEmployeetype(String employeetype) {
        this.employeetype = employeetype;
    }

    /**
     * @return the dept
     */
    public String getDept() {
        return dept;
    }

    /**
     * @param dept
     *            the dept to set
     */
    public void setDept(String dept) {
        this.dept = dept;
    }

    /**
     * @return the phoneextn
     */
    public int getPhoneextn() {
        return phoneextn;
    }

    /**
     * @param phoneextn
     *            the phoneextn to set
     */
    public void setPhoneextn(int phoneextn) {
        this.phoneextn = phoneextn;
    }

    /**
	 * @return the user
	 */
    public User getUser() {
	    return user;
    }

	/**
	 * @param user the user to set
	 */
    public void setUser(User user) {
	    this.user = user;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Employee [employeeType=");
        builder.append(employeetype);
        builder.append(", dept=");
        builder.append(dept);
        builder.append(", phoneextn=");
        builder.append(phoneextn);
        builder.append(", user=");
        builder.append(user);
        builder.append("]");
        return builder.toString();
    }

}

9.Now, we just need to call readJSONResponse:JsonToObjectExample to get Object of Employee.


import java.io.IOException;

import com.bs.genericjson.convertor.JsonToObject;
import com.bs.genericjson.module.Employee;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToObjectExample {
    public static void main(String[] args) throws JsonProcessingException, IOException {
        ObjectMapper mapper = new ObjectMapper();

        String jsonString = mapper.readTree(JsonToObjectExample.class.getClassLoader().getResourceAsStream("employee.json")).toString();
        System.out.println("JSON Input String :-" + jsonString);

        JsonToObject<Employee> jsonObject = new JsonToObject<Employee>();
        Employee employee = jsonObject.readJSONResponse(jsonString, "employee", Employee.class);
        System.out.println("POJO Object Result :- " +employee);

    }
}

10.Output


JSON Input String :-{"employee":{"employeetype":"Full Time","dept":"tech","phoneextn":1001,"user":{"userid":1,"firstname":"Shailendra","lastname":"Soni","gender":"Male"}}}
POJO Object Result :- Employee [employeeType=Full Time, dept=tech, phoneextn=1001, user=User [userid=1, firstname=Shailendra, lastname=Soni, gender=Male]]

11.You can get JSON either from HTTP, File or any other media. You need to create POJO of same and then just call readJSONResponse:JsonToObject which is return object of POJO class.

12.Git Repository :- https://github.com/sonishailendra/genericjson.git

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s