Click here to Skip to main content
15,884,629 members
Articles / Programming Languages / Java
Tip/Trick

Simple JSON REST Consumption with GSON API

Rate me:
Please Sign up or sign in to vote.
4.73/5 (9 votes)
10 Mar 2019CPOL 40.9K   7   3
This article shows how to use JSON response from REST service using Java GSON API.

Introduction

GSON is an open source Java API for serializing and deserializing JSON objects from and to Java objects, developed by Google. The purpose of this article is to provide a simple example of how to use this library.

Using the Code

GSON API could be found at maven repository. You can add the following section in your pom.xml in order to download gson.jar.

XML
<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.7</version>
</dependency>

For this example, we need a remote storage for our JSON objects. There is a free online tool for JSON response mocking http://www.json-gen.com/.

We created a simple Employee JSON object with the following structure:

JavaScript
{
  "id": 149859,
  "first_name": "Mike",
  "last_name": "Gonzalez",
  "date": "11/23/2016, 9:11:04 PM",
  "photo": "http://srcimg.com/100/150",
  "married": true
}

This JSON structure can be accessed via the following link:

We also need a class that will represent our Employee JSON object:

Java
public class Employee {
	private int id;
	private String firstName;
	private String lastName;
	private Date date;
	private String photo;
	private boolean married;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	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 Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public boolean isMarried() {
		return married;
	}
	public void setMarried(boolean married) {
		this.married = married;
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy, hh:mm:ss a", Locale.ENGLISH);
		
		builder.append("Id: ").append(id).append(", ")
			   .append("First Name: ").append(firstName).append(", ")
			   .append("Last Name: ").append(lastName).append(", ")
			   .append("Date: ").append(sdf.format(date)).append(", ")
			   .append("Photo path: ").append(photo).append(", ")
			   .append("Is Married: ").append(married);
		return builder.toString();
	}
}

As we can see, naming conventions for JSON object and Java object are not the same, so we cannot use default GSON deserializer. For that purpose, we need to create a new class that will implement our logic for deserializing.

Java
public class JsonDeserializerEmployee implements JsonDeserializer<Employee>{

	public Employee deserialize(JsonElement json, Type typeOfT, 
	JsonDeserializationContext context) throws JsonParseException {
		
	    JsonObject employeeJson = json.getAsJsonObject();
	    int id = employeeJson.get("id").getAsInt();
	    String firstName = employeeJson.get("first_name").getAsString();
	    String lastName = employeeJson.get("last_name").getAsString();
	    Date date = null;
	    
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy, hh:mm:ss a", Locale.ENGLISH);
			date = sdf.parse(employeeJson.get("date").getAsString() );
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
	    String photoPath = employeeJson.get("photo").getAsString();
	    boolean married =employeeJson.get("married").getAsBoolean();
	    
	    Employee employee = new Employee();
	    employee.setId(id);
	    employee.setFirstName(firstName);
	    employee.setLastName(lastName);
	    employee.setDate(date);
	    employee.setPhoto(photoPath);
	    employee.setMarried(married);
	    
	    return employee;
	}
}

And finally, code for the main class:

Java
public static void main(String[] args) throws IOException {
		
	String url = "http://json-gen.com/rest/service/get/otg3pqViiK13sxL1Zua2uSH";
		
	String content = fetchContent(url);
	Gson gson = new GsonBuilder().registerTypeAdapter(Employee.class, new JsonDeserializerEmployee())
			    .serializeNulls().create();

	Employee employee = gson.fromJson(content, new TypeToken<Employee>(){}.getType());
		
	System.out.println(employee);
}
	
private static String fetchContent(String uri) throws IOException {

	final int OK = 200;
	URL url = new URL(uri);
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();

	int responseCode = connection.getResponseCode();
	if(responseCode == OK){
		BufferedReader in = new BufferedReader(
				new InputStreamReader(connection.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
		
		return response.toString();
	}
		
	return null;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
Software Engineer, oriented to programming in C# and Java. Developing desktop and web apps, mainly using TDD approach. Learning and experimenting with JavaScript frameworks.

Comments and Discussions

 
QuestionHave you consider to post this as a tip? Pin
Nelek6-Dec-16 20:57
protectorNelek6-Dec-16 20:57 
AnswerRe: Have you consider to post this as a tip? Pin
Mirnes Mrkaljevic7-Dec-16 4:38
Mirnes Mrkaljevic7-Dec-16 4:38 
GeneralRe: Have you consider to post this as a tip? Pin
Nelek7-Dec-16 5:24
protectorNelek7-Dec-16 5:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.