ChatBot ( AI + NPL) + REST APIs

This is the simple application which has ChatBot and ChatBot interact with REST APIs ( NPL Engine) by sending User message, REST APIs has understood the message and reply back with using NPL+AI. ( Internally it is using Pattern matching).

This application is searching Resturant based on static data, it is a just platform to get an idea how ChatBot is working.  You can use as the platform and enhance it.

Technologies used in this article:

  • ChatBot ( Opensource Project :- https://bottr.co/) – It is used Node.js
  • RestEasy
  • Tomcat

Backend Services

I have created only one service, which except a message and processing message aginst static data.

File :- pom.xml

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.bs.rest</groupId>
	<artifactId>chatbot-npl-bot</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>ChatBot</name>
	<repositories>
		<repository>
			<id>MVN Repositories</id>
			<url>https://mvnrepository.com/artifact/</url>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>3.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson2-provider</artifactId>
			<version>3.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
	</dependencies>
</project>

Here is my API project structure,

Screen Shot 2017-05-27 at 3.32.27 PM

This application works on static data with predefined patterns, the first string is defining patterns and the second string is its respective answer/question.

File :- DataBuilder.java

		dataList.add(createSampleData("hi|hello|hey","Hello Mr. Shailendra Soni, How can I help you."));
		dataList.add(createSampleData("restaurants|restaurant|food","Do you want to try any new cuisine or dine in the regular restaurants you visited?"));
		dataList.add(createSampleData("new","Okay. That great! What kind of Food do you like? We have found some restaurants near by you which servers following foods Mexican/Italian/Chinese/Indian, Please choose anyone of them."));
		dataList.add(createSampleData("regular","Aha.. Let me look, As per past 3 months, you had visisted Italian/chinese, Please choose anyone of them."));
		dataList.add(createSampleData("maxican","Great Choice. Here are Maxican Resturants with offers 1. Armando's Mexican Food 2. Top Shelf Mexican."));
		dataList.add(createSampleData("italian","Awesome Choice. Here are Italian Resturants with offers 1. Tutti Santi by Nina 2. Romano's Macaroni Grill "));
		dataList.add(createSampleData("chinese","Super Choice. Here are Chinese Resturants with offers 1. Panda Express 2. Go Go China "));
		dataList.add(createSampleData("indian","Amazing Choice. Here are Indian Resturants with offers 1. Bawarchi Indian Cuisine 2. Marigold Maison "));
		dataList.add(createSampleData("offers|deal|coupons","Yes, There is one offer on some the restaurants too, Here is 1. If you spend $100, you will get 20% discount. Do you want to see all those Restaurants?"));
		dataList.add(createSampleData("yes","Here are Resturants list 1. Village Inn 2. Sonic Drive-In."));
		dataList.add(createSampleData("no","Have nice day Mr. Soni."));
		dataList.add(createSampleData("thanks|thank","It's my pleasure."));
		dataList.add(createSampleData("bye","Have nice day Mr. Soni."));
		dataList.add(createSampleData("great|awesome","That's my job. Thank You."));

Below code is responsible for finding particular sentence/answer based on the message from ChatBot.

It takes the message and then applies regex with using boundaries words and then join all those words with “|” character. The final String considers as the matcher.

Now, iterate on static data and compile the patterns and match with above final string. If its match then returns pattern name and respective value otherwise it will return “no found” as the pattern and “I’m afraid I don’t understand. I’m sorry!” as value.

File :- BotService.java

package com.bs.rest.service;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.bs.rest.data.DataBuilder;
import com.bs.rest.data.StaticData;
import com.bs.rest.model.ContentMatch;

public class BotService {

    public ContentMatch match(String content) {

        ContentMatch contentMatch = new ContentMatch();
        if (!StringUtils.isBlank(content)) {
            // word boundaries
            String[] words = content.trim().toLowerCase().split("\\b");
            List<String> tokens = Arrays.asList(words);
            String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
            Matcher matcher = null;
            Pattern pattern = null;
            for (StaticData sd : DataBuilder.getData()) {
                pattern = Pattern.compile(sd.getPattern());
                matcher = pattern.matcher(patternString);
                while (matcher.find()) {
                    contentMatch.setPattern(sd.getPattern());
                    contentMatch.setValue(sd.getValue());
                    return contentMatch;
                }

            }
        }
        // default set
        contentMatch.setPattern("notfound");
        contentMatch.setValue("I'm afraid I don't understand. I'm sorry!");
        return contentMatch;

    }
}

There are other java files too which you can check at my GitHub repository which is given at the then end of this blog.

ChatBot

Now, I have downloaded open source ChatBot application from below link, It runs on Node.js application, please go through below link for how to install and how to use it.

https://bottr.co/

Once I have installed “bottr”, then open “index.js” from the installation directory and modified for connecting to REST APIs, get the value and same is displaying back to User.

File :- index.js

const Bottr = require('bottr')
const BottrApp = require('bottr-app')
const request = require('request');
const bot = new Bottr.Bot();
var fs = require('fs');
var path = require('path');
var sessiontest;
bot.on('message_received', function(message, session) {
    sessiontest = session;
    var propertiesObject = { content: message.text };
    console.log(propertiesObject);
    var options = {
        url: 'http://localhost:8080/poc-bot/bot',
        qs: propertiesObject
    };
    request.get(options, function(err, response, body) {
        if (err) { console.log(err); return; }
        var jsonData = JSON.parse(body);
        sessiontest.send(jsonData.value);
    });
})
bot.use(new BottrApp())
bot.listen()

Bottr runs on localhost:3000. Below image is showing actual conservation between the End User and chatbot.

Screen Shot 2017-05-27 at 6.39.42 PM.png

This is the very simple way to represent ChatBot with natural language processing.

Links :-

Chatbot-api :- https://github.com/sonishailendra/chatbot-api

Bottr :- https://bottr.co/

RestClient Framework With Using HTTPClient

RESTClient Framework

Why Need It?

Recently I have worked on to consuming Rest APIs. We have different producers who expose REST APIs so instead of creating the different interface for all different REST APIs, I have decided to build a framework which can consume REST APIs and Return the object based on what I want.

So I have started exploring clients, I have explored

  • RESTEasy
  • Jersey
  • HTTPClient
  • Spring REST Template

After some research and finding some issue to conflict specification, I decided to use HTTPClient.

Why I choose HTTPClient?

RESTEasy and Jersey latest version have implemented JAX-RS 2.0 client specification which is part of J2EE/JAVAEE 7 and I really want use Specification but existing code based has been supported JAVAEE 6 so I could not use these two frameworks, however I can use their old/archive build but that too much old which I would like to avoid.

So finally I have decided to go with Apache HTTP Client which is not the specification but some of the frameworks are using as under the hood. And it is also seamless implementation and wide open community.

Here is REST Client Framework,

  • Here is pom.xml dependencies,

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jackson.version>2.8.5</jackson.version>
<httpclient.version>4.4</httpclient.version>
</properties>

<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>

<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>

</dependencies>

  • First thought came into my mind is that Developer should about that they are trying to use this Framework by passing request object and expecting response should be in-line with JSON format. So I have created below hierarchy for the JSON parsing,
package rest.model;
/**
* Develoepr need to aware about what they could pass to RestClient.
* @author Shailendra Soni
*
*/
public interface JSONPojo {

}

  • JSON request like if you want to call POST with passing values as JSON into Body.

package rest.model;
/**
* Implement this interface , if REST API is expecting JSON in the request body part.
* @author Shailendra Soni
*
*/
public interface JSONRequest extends JSONPojo{

}


package rest.model;
/**
* Implement this interface at POJO which member variables are corrosponding to JSON.
* @author Shailendra Soni
*
*/
public interface JSONResponse extends JSONPojo{

}

  • Below is convertor class which convert from JSON to POJO and POJO to JSON

package rest.restclient;

/**
* Convert from POJO to JSON and JSON to POJO
* @author Shailendra Soni
*/
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
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;

import rest.model.JSONPojo;

public class JSONConvertor<T extends JSONPojo> {

private static final String EMPTY_STRING="";

public T jsonToPojo(String jsonString, Class<T> 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.traverse(), classzz);
}

public String pojoToJson(T t) throws JsonProcessingException {
if (t == null) {
return EMPTY_STRING;
}
ObjectMapper objMapper = new ObjectMapper();
return objMapper.writeValueAsString(t);
}

}

  • Below is RestClient implementation, right now I am having POST and GET methods implementation but if someone wants to extend it then please implement new methods into this framework by forking the GIT repository.

package rest.restclient;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import rest.exception.APIException;
import rest.model.JSONPojo;
import rest.model.JSONRequest;
import rest.model.JSONResponse;

/**
* This class responsibility to call REST API and Response based on T.
*
* @author Shailendra Soni
*
* @param <T> :- extends JSONResponse
*/
public class RestClient<T extends JSONResponse> {

private String restURL;

private int timeOut = 0; // in second

public RestClient(String restURL) {
this.restURL = restURL;
}

public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}

/**
* Rest GET implementation
*
* @param clazz
* @param headers
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws IOException
* @throws APIException
*/
public T getRest(Class<T> clazz, Map<String, String> headers)
throws InvalidKeyException, NoSuchAlgorithmException, URISyntaxException, ClientProtocolException, IOException, APIException {

CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet(this.restURL);
setTimeOut(httpGet);
setHeadder(httpGet, HttpGet.METHOD_NAME, headers);

CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
String result = getResponseInString(httpResponse);
System.out.println("Response :- " + result);
JSONConvertor<T> jsonConvertor1 = new JSONConvertor<T>();
T t = jsonConvertor1.jsonToPojo(result, clazz);
return t;
} else {
StringBuilder message = new StringBuilder("Status Code :- ");
message.append(httpResponse.getStatusLine().getStatusCode());
message.append(" Message :- ");
message.append(getResponseInString(httpResponse));
throw new APIException(message.toString());
}
} finally {
if (httpClient != null) {
httpClient.close();
}

}

}

/**
* This method server POST method of REST API.
*
* @param requestObject
* - Convert POJO to JSON :- JSONRequest
* @param class1
* @param headers
* :- Map<String,String>
* @return T :- Response JSON to POJO
* @throws IOException
* @throws APIException
* @throws URISyntaxException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public T postRest(JSONRequest requestObject, Class<T> clazz, Map<String, String> headers)
throws IOException, APIException, InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();

JSONConvertor<JSONPojo> jsonConvertor = new JSONConvertor<JSONPojo>();
StringEntity jsonRequest = new StringEntity(jsonConvertor.pojoToJson(requestObject));

HttpPost httpPost = new HttpPost(this.restURL);
setTimeOut(httpPost);
setHeadder(httpPost, HttpPost.METHOD_NAME, headers);
httpPost.setEntity(jsonRequest);

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
String result = getResponseInString(httpResponse);
JSONConvertor<T> jsonConvertor1 = new JSONConvertor<T>();
T t = jsonConvertor1.jsonToPojo(result, clazz);
return t;
} else {
StringBuilder message = new StringBuilder("Status Code :- ");
message.append(httpResponse.getStatusLine().getStatusCode());
message.append(" Message :- ");
message.append(getResponseInString(httpResponse));
throw new APIException(message.toString());
}
} finally {
if (httpClient != null) {
httpClient.close();
}

}
}

private void setHeadder(HttpRequestBase httpRequest, String httpVerb, Map<String, String> headers)
throws InvalidKeyException, NoSuchAlgorithmException, MalformedURLException, URISyntaxException {

httpRequest.addHeader("content-type", ContentType.APPLICATION_JSON.getMimeType());
if (headers != null && !headers.isEmpty()) {
for (String keyHeader : headers.keySet()) {
httpRequest.addHeader(keyHeader, headers.get(keyHeader));
}
}
}

private void setTimeOut(HttpRequestBase httpRequest) {
if (this.timeOut > 0) {
httpRequest.setConfig(getConfigurationForTimeOut());
}
}

private String getResponseInString(CloseableHttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
}

private RequestConfig getConfigurationForTimeOut() {
RequestConfig config = RequestConfig.custom().setConnectTimeout(this.timeOut * 1000).setConnectionRequestTimeout(this.timeOut * 1000).setSocketTimeout(this.timeOut * 1000)
.build();
return config;
}
}

  • By using this framework, developer do not need to explore REST client and also developer do not worry about following things
    • Convert request object to JSON
    • Core implementation to calling REST APIs
    • Convert JSON to expected class object
    • Connection Timeout implementation
  • Below is my implementation of RESTClient Framework
import java.util.HashMap;
import java.util.Map;

import com.americanexpress.sis.rest.model.JSONRequest;
import com.americanexpress.sis.rest.model.JSONResponse;
import com.americanexpress.sis.rest.restclient.RestClient;

public class TestRestClient {

public static void main(String[] args) throws Exception {
String restURL = "http://localhost:8080/RESTfulExample/json/product/postproduct";

Product p = new Product();

RestClient<Product> rc = new RestClient<Product>(restURL);
Product productResponse = rc.postRest( p, Product.class, getHeaders());
System.out.println("Product Information :- " + ps.toString());
}

public static Map<String,String> getHeaders(){
Map<String,String> headers = new HashMap<String, String>();
headers.put("accountid", "testrest");
return headers;
}

}
class Product implements JSONResponse, JSONRequest{

private String name = "testing";
private int qty = 111;

public String getName() {
return name;
}

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

public int getQty() {
return qty;
}

public void setQty(int qty) {
this.qty = qty;
}

@Override
public String toString() {
return "Product [name=" + name + ", qty=" + qty + "]";
}
}

    It’s Easy…
  • This is small Framework, it needs to implement more things like
    • Security:- Most of REST APIs are secure, so need to pass certificate while calling them.
    • PUT and Delete REST methods implementations
    • Cookies Implementation

    If anybody interested to implementing above things then please contact me at soni.shailendra@outlook.com for helping me to enhance this framework or fork GIT repo.

  • GIT repo :- https://github.com/sonishailendra/restclient

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&lt;T extends JsonPojoParserInt&gt; {

/**
* 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&lt;Employee&gt; jsonObject = new JsonToObject&lt;Employee&gt;();
        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