Home » Enterprise Java » gwt » GWT Json Example

About Mohammad Meraj Zia

Senior Java Developer

GWT Json Example

In this example we will learn how to retrieve JSON data using GWT. The Google Web Toolkit is a development framework for creating Ajax-enabled web applications in Java. JSON is a universal, language-independent format for data. It is similar to XML, but it does not uses tabs. Tools and technologies used in this example are Java 1.8, Eclipse Luna 4.4.2, Eclipse GWT Plugin 2.6

1. Introduction

If your GWT application needs to communicate with a server, but you can’t use Java servlets on the backend — or if you simply prefer not to use RPC — you can still perform HTTP requests manually. GWT contains a number of HTTP client classes that simplify making custom HTTP requests to your server and optionally processing a JSON- or XML-formatted response.

2. JSON

JSON is based on object-literal notation of JavaScript. Therefore the format is much simpler than XML and uses less characters/size to represent data. JSON format is based on the syntax and data types of the JavaScript language. It supports strings, numbers, booleans and null values. You can also combile multiple values into arrays and objects. JSON objects are simply unordered sets of name/value pairs. The name is always string and the value is any other valid JSON type (even another object)

Let say we want to represent the customer address data. Below is the representation in XML

<Address>
    <AddressLine1>Fleet Street</AddressLine1>
    <AddressLine2>Oxford</AddressLine2>
</Address>

The same thing will be represented in JSON as shown below

{
"Address": {
  "AddressLine1": "Fleet Street",
  "AddressLine2": "Oxford"
    }
}

3. Parsing

You can parse JSON Strings and convert them to a JavaScriptObject using com.google.gwt.core.client.JsonUtils. This class provide JSON-related utility methods. Typically, you will receive JSON data as the response text of an HTTP request. Thus, you’ll first have to convert that String into a Object that you can work with using a method defined in JsonUtils class.

Below we will see what classes have been used for this example.

3.1 Configuration

Below is the GWT configuration file.

JsonGwtExample.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.6.0//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.6.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='jsongwtexample'>

  <inherits name='com.google.gwt.user.User'/>
  <inherits name="com.google.gwt.json.JSON" />
  <inherits name="com.google.gwt.http.HTTP"/>

  <inherits name='com.google.gwt.user.theme.clean.Clean'/>

  <entry-point class='com.javacodegeeks.client.JsonGwtExample'/>

  <source path='client'/>
  <source path='shared'/>

  <add-linker name="xsiframe"/>
</module>

<inherits name="com.google.gwt.json.JSON" /> is required to add JSON capabilities in the GWT application

3.2 Client

Below is the Entry point class.

JsonGwtExample.java

package com.javacodegeeks.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad().
 */
public class JsonGwtExample implements EntryPoint {

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {
    Button submit = new Button("JSON");
    submit.addClickHandler(new ClickHandler() {
      
      @Override
      public void onClick(ClickEvent event) {
        parseData();        
      }
    });
    
    RootPanel.get("container").add(submit);
  }
  
  private void parseData() {
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/jsongwtexample/greet");
    try {
      requestBuilder.sendRequest(null, new RequestCallback() {
        
        @Override
        public void onResponseReceived(Request request, Response response) {
          JSONValue jsonValue = JSONParser.parseStrict(response.getText());
          
          JSONObject customerObject = jsonValue.isObject();
          JSONArray jsonArray = customerObject.get("customers").isArray();
          
          StringBuilder builder = new StringBuilder("** CUSTOMER DATA ** \n");        
          builder.append(jsonArray.get(0).isObject().get("FirstName").isString().stringValue()).append(" ");
          builder.append(jsonArray.get(0).isObject().get("Surname").isString().stringValue());
          builder.append("\n");
          builder.append(jsonArray.get(1).isObject().get("FirstName").isString().stringValue()).append(" ");
          builder.append(jsonArray.get(1).isObject().get("Surname").isString().stringValue());
          
          Window.alert(builder.toString());
          
        }
        
        @Override
        public void onError(Request request, Throwable exception) {
          Window.alert("Some error occurred: " + exception.getMessage());
          
        }
      });
    } catch (RequestException e) {
      e.printStackTrace();
    }
  }
}

In this class first we create a Button (Button submit = new Button("JSON");), then we attach a click handler to this button. com.google.gwt.http.client.RequestBuilder class is used for constructing the Request objects. Modules that use this class should inherit com.google.gwt.http.HTTP.

<module>
  <!-- other inherited modules, such as com.google.gwt.user.User -->
  <inherits name="com.google.gwt.http.HTTP"/>
  <!-- additional module settings -->
</module>

We will create the Request builder object by calling the below constructor new RequestBuilder(RequestBuilder.GET, "/jsongwtexample/greet"). The first argument is the HTTP method to use for the request. The second argument is the URL that has already has already been encoded.

Then we will call call the sendRequest() method on this object. The first argument of this method is the request data. We don’t need to pass any request data for this example so it’s null. The second argument is the com.google.gwt.http.client.RequestCallback. This method sends an HTTP request based on the current builder configuration with the specified data and callback. If no request headers have been set, the header Content-Type will be used with a value of text/plain; charset=utf-8. This method does not cache requestData or callback.

We create the sample data using the JSON classes. First we parse the response data with com.google.gwt.json.client.JSONParser. This class parses the string representation of a JSON object into a set of JSONValue-derived objects. The parseStrict() method evaluates a JSON string and returns its JSONValue representation. The browser’s JSON.parse function is used. If some error occurred then we will display the error message in a pop-up window – Window.alert("Some error occurred: " + exception.getMessage());

3.3. Server

Below is the server side class used for this example.

GreetingServiceImpl.java

package com.javacodegeeks.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * The server-side implementation of the RPC service.
 */
public class GreetingServiceImpl extends HttpServlet {

  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    JSONObject responseObject = new JSONObject();
    
    List customers = new ArrayList();
    try {      
      JSONObject customerObject1 = new JSONObject();
      
      customerObject1.put("FirstName", "John");
      customerObject1.put("Surname", "Travolta");
      customers.add(customerObject1);
      
      JSONObject customerObject2 = new JSONObject();
      
      customerObject2.put("FirstName", "Tom");
      customerObject2.put("Surname", "Cruise");
      customers.add(customerObject2);      
        
      responseObject.put("customers", customers);    
    } catch (JSONException je) {
      throw new ServletException(je);
    }    
    
    PrintWriter writer = response.getWriter();
    writer.write(responseObject.toString());
    writer.flush();    
  }
}

This is the servlet class which sets the JSONObject in the response.

3.3.1 JSON Object

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods. A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

The generic get() and opt() methods return an object, which you can cast or query for type. There are also typed get and opt methods that do type checking and type coercion for you. The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such as null.

The put methods add or replace values in an object. For example,

myString = new JSONObject().put("JSON", "Hello, World!").toString(); produces the string {"JSON": "Hello, World"}. The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

  • An extra , (comma) may appear just before the closing brace.
  • Strings may be quoted with ‘ (single quote).
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.
  • Keys can be followed by = or => as well as by :.
  • Values can be followed by ; (semicolon) as well as by , (comma).

3.4 web.xml

Below is the web.xml file configuration.

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

 <!-- Servlets -->
 <servlet>
 <servlet-name>greetServlet</servlet-name>
 <servlet-class>com.javacodegeeks.server.GreetingServiceImpl</servlet-class>
 </servlet>
 
 <servlet-mapping>
 <servlet-name>greetServlet</servlet-name>
 <url-pattern>/jsongwtexample/greet</url-pattern>
 </servlet-mapping>
 
 <!-- Default page to serve -->
 <welcome-file-list>
 <welcome-file>JsonGwtExample.html</welcome-file>
 </welcome-file-list>

</web-app>

4. Compile

To compile the application right click on the project and select ‘Google’ ==> ‘GWT Compile’.

Figure 1. GWT Compile

Figure 1. GWT Compile

Then another window will be displayed. Click ‘Compile’

5. Running the application

To run the application right click on the project and select ‘Run As’ ==> ‘Web Application (Classic Dev Mode)’. Eclipse will display a URL in the ‘Development Mode’ tab. Copy this URL and paste it on you favourite browser. Remove the part after ‘.html’ and click enter.  You will see the button displayed on the screen. Click on the button. Magic!!!,

Figure 2. Run

Figure 2. Run

6. Download the source file

This was an example of GWT JSON.

Download
You can download the full source code of this example here: JsonGwtExample. Please note that the jar files have been removed to save space.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments