Click here to Skip to main content
13,899,794 members
Click here to Skip to main content
Add your own
alternative version

Stats

24.9K views
6 bookmarked
Posted 5 Dec 2016
Licenced CPOL

Simple JSON REST Consumption with GSON API

, 10 Mar 2019
Rate this:
Please Sign up or sign in to vote.
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.

<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:

{
  "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:

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.

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:

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)

Share

About the Author

Mirnes Mrkaljevic
Bosnia and Herzegovina Bosnia and Herzegovina
Software Engineer, oriented to programming in C# and Java. Developing desktop and web apps, mainly using TDD approach. Learning and experimenting with JavaScript frameworks.

You may also be interested in...

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
memberMirnes 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190306.1 | Last Updated 10 Mar 2019
Article Copyright 2016 by Mirnes Mrkaljevic
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid