Android App Development

Android App Development : Use Gson To Work With JSON

This post is dedicated to include topics related to GSON for the Android app development. This is a vital and essential part of Java and Android developers’ toolkit.

As we know Java is all about object, and often, we need to convert data from JSON to Java Objects and Java Object to JSON. There are many alternatives to JSON, i.e OData, Rest XML. But if we are storing data of 8.5 kb in OData, then the same data can be compressed and stores it in REST XML format in about 1.2 kb whereas JSON format in about 639 bytes which is very less. Due to this reason JSON is preferred.

Note: It would be easier to grasp the following concepts with prior knowledge in Java basics and AsyncTask concepts.


Introduction to JSON (JavaScript Object Notation)

JSON (JavaScript Object Notation) is a lightweight data interchange format which is well organized and easy to access. In general words, we can say that JSON is a syntax for exchanging human readable information between servers, which acts as a backend in Android smartphones where we can access the data logically.

Benefits of JSON

The following are the advantages of JSON:

  1. It’s easy to read and write data.

  2. Its fast & compact’.

  3. Ideal for ordered lists or key/values.

  4. Maps perfectly to most of the programming languages with mutable arrays and dictionaries(hash tables)

JSON is mostly used for serializing and transmitting structured data over a network connection. The below image shows a general structure of the JSON data.

We need to convert Java objects into JSON and JSON string into Java object to speed up the process of execution (data fetching from Server) as well as for usage in Java program since Java is pure object-oriented language. Many Java libraries are available for this specific conversion, but GSON stands out among the few which does not require any pre-annotated metatags that can be added to your code and applied to the package declarations, type declarations, constructors, methods, fields, parameters and variables in the source code of Java classes in any way. So let’s discuss what GSON is , its goal and features.

Introduction to GSON

GSON also known as Google GSON, is an open-source Java library that can be used to convert Java Objects into JSON (JavaScript Object Notation) & vice versa.

GSON objects can be created in two ways. They are as follows:

  1. To create a GSON object for faster coding
    Gson gson = new Gson();
  2. To create a GSON object using GsonBuilder
Gson gson = new GsonBuilder()
.disableHtmlEscaping() // By default, Gson escapes HTML characters such as < >
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
// Configures Gson to apply a specific naming policy to an object's field during
//serialization and deserialization.
.setPrettyPrinting() // To generate a more readable and pretty looking JSON
.serializeNulls() //  Configure Gson to serialize null fields
.create();

Objectives of GSON

  • Provides easy to use methods like toString() and constructor (factory method) to convert Java to JSON and vice-versa.

  • Provides simple toJson () and fromJson () methods to convert Java objects to JSON and vice-versa. The code snippet is as shown below:

To convert the java objects to JSON format, use toJson() method:

Cast cast = new Cast();
cast.setId(1);
cast.setCharacter("Logan / Wolverine");
cast.setName("Hugh Jackman");
Gson gson = new Gson(); //GSON object
System.out.println(gson.toJson(cast));
/**
Output:
{"id":1,"character":" Logan / Wolverine","name":" Hugh Jackman"}
*/

To convert the JSON to java object, use fromJson() method:

Gson gson = new Gson(); //GSON object
 
System.out.println(
gson.fromJson("{"id":1,"character":" Logan / Wolverine","name":" Hugh    Jackman"}",  Cast.class));
     
/**
Output:
Cast [id=1, character= Logan / Wolverine, name= Hugh Jackman]
*/
  • Allow custom representation for objects.

  • Generate compact and readability JSON output.

GSON Features

  • GSON can handle collections, generic types, and nested classes. Collections are generic and the generic type information is not maintained in the json. We therefore pass the type while deserializing list. If the Collection has different types of objects then there is no way to serialize it. Thats the reason why Serializing and deserializing classes with generic types is non-trivial since generic type information is lost while serializing. GSON provides a class called com.google.gson.reflect. TypeToken to store generic types.

The below example shows how to use the TypeToken class to serialize and deserialize Classes with generic types.

// create an animal class that is of type dog.
Animal<dog> animal = new Animal<Dog>();
// Create a Dog instance
Dog dog = new Dog("I am a dog");
animal.setAnimal(dog);
Gson gson = new Gson();
// Define a Type that is an Animal of type dog.
Type animating = new Type Token<Animal<Dog>>() {
}.getType();
// We first convert the animal object to a json and then read the json back.
//However we define the json to be of Animal type
Animal animal1 = gson.fromJson (Jason. toJson (animal, animalType), Animal. class);
System.out.println(animal1.get().getClass()); 
/** In contrast to above where we read the json back using the Animal type,here we read the json back as the custom animalType Type. This gives Gson an idea of what the generic type should be. */
Animal animal2 = gson.fromJson(gson.toJson(animal), animalType);
System.out.println(animal2.get().getClass());
  • When deserializing, Gson is navigating the type tree of the object which is being deserialized. This results in ignoring the extra fields present in the JSON input.
  • GSON is highly customizable, you can specify compact/pretty printing i.e. whether you want compact or readable output, how to handle null object fields by default they are not present in the output, Rules of what fields are intended to be excluded from (de)serialization & how to convert Java field names.
  • User can write a custom serializer and/or deserializer so that they can control the whole process. You need to follow below steps to create a custom serializer & deserializer

Tutorial – Steps to Write a Serializer and Deserializer Code

Let’s write a serializer and deserializer code for java.util.Date class, which will help writing the Date format in “dd/MM/yyyy” format. The steps are as follows:

Step 1 : Let’s create DateSerializer.java

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
 
public class DateSerializer implements JsonSerializer<Date>
{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   
public JsonElement serialize(Date date, Type typeOfSrc,         JsonSerializationContext context)
   {
      return new JsonPrimitive(dateFormat.format(date));
   }
}

Step 2 : Let’s create DateDeserializer.java

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
 
public class DateDeserializer implements JsonDeserializer<Date>
{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   
public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context)
   {
      try
      {
         return dateFormat.parse(dateStr.getAsString());
      } 
      catch (ParseException e)
      {
         e.printStackTrace();
      }
      return null;
   }
}

Step 3 : Now you can register these serializer and deserializer with GsonBuilder as shown below:Android Programming

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

Prerequisites for adding the GSON Library in project

The gson-2.4.jar file is required for convertion of Java Objects into JSON (JavaScript Object Notation) & vice versa. If you don’t have one, you can download it from here

Follow the below mentioned steps to configure your project with this library:

Step 1:  Select Android view from the drop down menu from the project explorer on the left hand side of the screen

Step 2: Right click on the option ‘app’ and select New -> Module

Step 3: Select Phone and Tablet application from the dialog box. Further, select Import .JAR or .AAR Package and then click on Next.

Step 4: In the next dialog box, click browse on the right ride of the File Name field. Browse and select the gson-2.4.jar file from it.

Step 5: Wait for the project to complete the build process, after which you can see ‘gson-2.4’ in the project explorer. The error still exists, so let’s go and add the dependency to the project in the upcoming steps.

Step 6: Right click on app in the project explorer, select Open Module setting or press F4.

Step 7: In the Module Settings dialog box, select the Dependencies tab, click the + icon on the top right hand side of the dialog and select Module Dependencies.

Step 8: Now a dialog box will popup showing the Modules in the project. Select the module gson-2.2.4 and click on ok.

Step 9: Again, click on Apply and then on OK.

Step 10: Now wait for the build to complete. On completion, the rotating throbber stops indicating that the jar file is integrated.

Building an Android App Using GSON

Hope the explanation on what GSON is all about was clear enough. Let’s now discuss in detail with one live example of a movie cast info and how it can be used while coding android program.

GSON Cast Example

Here is a sample of the JSON data returned from the below API call to view the cast of a specific movie (based on a movie id-76170 as shown in the screenshot below): http://api.themoviedb.org/3/movie/76170/credits?api_key=8496be0b2149805afa458ab8ec27560c

{
id: 76170,
cast: 
[
{
cast_id: 37,
character: "Logan / Wolverine",
credit_id: "536e7d3dc3a368122600ce7b",
id: 6968,
name: "Hugh Jackman",
order: 0,
profile_path: "/oVlS7sDpnWbNBzCxwjnWceSfwrl.jpg"
},
{
cast_id: 13,
character: "Mariko",
credit_id: "52fe492ac3a368484e11d99b",
id: 1156024,
name: "Tao Okamoto",
order: 1,
profile_path: "/ahbByaizp6xLkakmTWebPC57v06.jpg"
},……
]
}

NOTE: In JSON, ‘[‘stands for JSON array and ‘{‘stands for JSON object.

Now we need to create a class ‘CastJson’ and annotate fields with the SerializedName. SerializedName is an annotation that indicates that the member should be serialized to JSON with the provided name value as its field name.

CastJson.java

import com.google.gson.annotations.SerializedName;
public class CastJson { 
//Create Serialized Name for all fields
    @SerializedName("cast_id")
    private String cast_id;
    @SerializedName("character")
    private String character;    
    @SerializedName("name")
    private String name; 
    public CastPost(String cast_id, String character, String name) {
        this.cast_id = cast_id;
        this.character = character;
        this.name = name;
    }
 // Create setters & getters for all fields
    public String getCast_Id() {
        return Cast_Id;
    }
    public void setCast_Id(String cast_id) {
        this.cast_name = cast_name;
    }
    public String getCharacter() {
        return character;
    }
    public void setCharacter(String character) {
        this.character = character;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = description;
    }
}

JsonAPI.java – Create JsonAPI.java class to perform an HTTP request and retrieve the resource as a stream.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class JsonAPI {
   private static Reader reader=null;
 
   public static Reader getData(String SERVER_URL) {
  try {
   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(SERVER_URL);
   HttpResponse response = httpClient.execute(httpPost);
   StatusLine statusLine = response.getStatusLine();
 
   if (statusLine.getStatusCode() == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       reader = new InputStreamReader(content);
    } else {
Log.e("error:", "Server responded with status code: "+ tatusLine.getStatusCode());
    }
 
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
          e.printStackTrace();
    }
    return reader;
    } 
}

MainActivity.java – Create MainActivity.java class and create GSON instance to get data in required format.

//An Asynchronous Task of MainActivity
new AsyncTask<Void,Void,Void>(){
 
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog=new ProgressDialog(MyActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
 
            @Override
            protected Void doInBackground(Void... voids) {
//Reading data from API
Reader reader= API.getData("http://api.themoviedb.org/3/movie/76170/credits?api_key=8496be0b2149805afa458ab8ec27560c");
 
//Get the ListType Name from ArrayList
                Type listType = new TypeToken<ArrayList<CastJson>>(){}.getType();
                castJson ArrayList = new GsonBuilder().create().fromJson(reader, listType);
 
                castList=new StringBuffer();
                for(CastPost cast: castPostArrayList){
                castList.append("\n Cast Id: "+post.getCast_Id ()+
                                "\n Character: "+post.getCharacter()+
                                "\n Credit Id: "+post.Credit_Id()+
                                "\n Name: "+post.getName()+"\n\n");
                }
                return null;
            }
 
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                progressDialog.dismiss();
                txtCastList.setText(castList);
            }
        }.execute();

App Screen Shot

The final output after following above process will look something as shown below:

You are almost done with coding now it’s time to test it. Run your project and test the application. At the initial stage you might get some errors but keep working on your code as it takes time to perfect it. Always use LogCat to debug your application, and if you cannot solve errors, find a suitable solution on stackoverflow.

If you are still facing issues email the Problem Statement, Problem Description and Screenshot of the error to [email protected] and we will gladly help you out!

Keep visiting our website Acadgild for more updates on Android and other technologies. Click here to learn Android App Development.

Android Programming

One Comment

  1. Pingback: 10 thư viện Android hữu ích dành cho Developers

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Related Articles

Close
Close