I am going to demonstrate how to consume rest API service Using Google Json jar that GSON jar .First you need to down the GSON jar .I am using gson-2.8.6.jar for my demo.
Rest service that i am is hosted at http://localhost:8080/employees .when hit GET request to this in postman or in browser i get response as below.
Response-
{
"employeeList": [
{
"employeeId": "1234",
"employeeName": "Dhiraj Shigavi",
"departmentName": "Information technology"
},
{
"employeeId": "7777",
"employeeName": "John Den",
"departmentName": "Electronic andtele communication"
}
]
}
To Consume this in java follow below steps.
1. create java project in jdeveloper ( you can user any IDE of your choice).
2.add the GSON jar file downloaded in project properties as below
3. Create java Class and name it ConsumeRestServiceWrapper.java.
4. Now first we need to understand the response and create java equivalent classes of it so we can parse the response using Gson jar file
In this case my response contains employeeList which is list so i will create a class which contains list object of employeeList ,now type of List object contains employeeId,employeeName,departmentName so will create another class which will have these three names of String object in as below.
So My Employee Class is as below.
public class Employee {
private String employeeId;
private String employeeName;
private String departmentName;
public Employee(String employeeId, String employeeName, String departmentName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.departmentName = departmentName;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Employee() {
super();
}
}
My EmployeeResponse class will contain List<Employee> with name employeeList.
Please note here name has to match with name in your rest response.
import java.util.List;
public class EmployeeResponse {
List<Employee> employeeList;
public EmployeeResponse() {
super();
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
}
Now main part is to write method in service wrapper class which will call the service and populate the data in object of EmployeeResponse class.
I have written getEmployees method which returns me object of EmployeeResponse created above.
Please note below line which populated the String response into Object that we can use in object format
EmployeeResponse employeeResponse = new Gson().fromJson(response.toString(), EmployeeResponse.class);
package com.service;
import com.google.gson.Gson;
import com.payload.Employee;
import com.payload.EmployeeResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ConsumeRestServiceWrapper {
public ConsumeRestServiceWrapper() {
super();
}
public static void main(String[] args) {
ConsumeRestServiceWrapper service = new ConsumeRestServiceWrapper();
try {
EmployeeResponse response = service.getEmployees();
if (response != null) {
if (response.getEmployeeList() != null && response.getEmployeeList().size() > 0) {
System.out.println("Employee list");
System.out.println("*****************");
for (Employee e : response.getEmployeeList()) {
System.out.println("Employee Id-" + e.getEmployeeId());
System.out.println("Employee Name-" + e.getEmployeeName());
System.out.println("Employee Department-" + e.getDepartmentName());
System.out.println("*****************");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public EmployeeResponse getEmployees() throws Exception {
URL url = new URL(null, "http://localhost:8080/employees", new sun.net.www.protocol.http.Handler());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
int responseCode = conn.getResponseCode();
System.out.println("URL...: " + url + " Response Code..: " + responseCode);
if (responseCode >= 200 && responseCode < 300) {
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String line;
StringBuffer response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
System.out.println("Rest response for employee is -" + response);
EmployeeResponse employeeResponse = new Gson().fromJson(response.toString(), EmployeeResponse.class);
return employeeResponse;
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
StringBuffer errorResponse = new StringBuffer();
while ((line = in.readLine()) != null) {
errorResponse.append(line);
}
in.close();
throw new RuntimeException(conn.getResponseCode() + " Invalid Response " + errorResponse);
}
}
}
when i run above class i get response as below
Some of rest service response just contains the list without the name as below
In this case when you run above code ,you would get exception as com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
so change the line in getEmployees method as below and it will directly populate in List<Employee>
List<Employee> employeeResponse = new Gson().fromJson(response.toString(), List.class);
hope this helps to know how to consume rest API using Gson jar file.