Using GSON in Android – Simple Demo

By | January 19, 2017

GSON is open source Java library developed by Google. It is an API for converting a Java object to json representation and viceversa.

Uses

  • Converts any Java object i.e new object or any existing/legacy object, to JSON and vice-versa.
  • Finest support for generic objects
  • Simple, convenient methods for conversions
  • No need of any annotation for fields for conversions
  • All the fields by default are included in conversions even private fields
  • If don’t want to include the field in conversion, use transient modifier for that field
  • It handles the null fields gracefully, by not including them in serialization output but during deserialization it is initialized back to null

Gradle Changes

Open your build.gradle and add these lines.

dependencies {
    compile 'com.google.code.gson:gson:2.4'
}

Usage

For conversion of an object to/from json, you need to use the Gson class and its following 2 methods.

toJson() => converts an object provided to json string, takes object to be converted as argument and returns the json representation string

fromJSon() => converts the json string to object, takes first param as json string as object and class literal of destination object and returns the destination object

You can use Gson instance/object multiple times as it does not maintain any state.

Model Class

I have created a model class User which looks like this.

package gson_demo.coderzheaven.com.gsondemo;

public class User {

    private String firstName, lastName;

    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;
    }
}

Implementation

Model to Json using GSON.

        Gson gson = new Gson();

        User user = new User();
        user.setFirstName("Coderz");
        user.setLastName("Heaven");

        String json = gson.toJson(user);
        Log.i("GSON", "Converted to JSON : " + json);

JSON String to Model Object.


        user = gson.fromJson(json, User.class);
        Log.i("GSON", "BACK TO MODEL OBJECT -> 
		             FirstName : " + user.getFirstName() + ", 
					 LastName : " + user.getLastName());

For generic objects

For converting back the generic object to java object from json representation, we need to use use extra object as shown in follows

Type collectionType = new TypeToken< { generic-object-with-type-information }>(){}.getType();

You need to provide the destination class type to TypeToken type parameter information as shown above. This is to form the Type instance and this we need to pass it to fromJson() method as second argument.

Following listing shows example for conversion of generic classes or the classes from collections framework to/from json

Model Class

public class GenericModel<T> {
	  T value;
	  
	  public GenericModel(T value) {
		super();
		this.value = value;
	  }
	  
	  @Override
	  public String toString() {
		return "Model2 [value=" + value + "]";
	  }
}

Generic Implementation

	Gson gson = new Gson();

	// a generified object
	GenericModel<Integer> model = new GenericModel<>(12);

	// converting to json representation
	String json = gson.toJson(model);
	Log.i("GSON", "json representation :" + json);

	// converting back to object
	Type collectionType = new TypeToken<GenericModel<Integer>>() {}.getType();
	GenericModel<Integer> modelObj = 
					  gson.fromJson(json, collectionType);
	Log.i("GSON", "converted object representation: " + modelObj);

	// for collection framework objects
	List<String> listOfString = new ArrayList<>();
	listOfString.add("Coderz");
	listOfString.add("Heaven");

	// conversion to json
	String jsonStr = gson.toJson(listOfString);
	Log.i("GSON", "json representation :" + jsonStr);

	Type collectionType2 = new TypeToken<List<String>>() {}.getType();
	List<String> listObj = gson.fromJson(jsonStr, collectionType2);
	Log.i("GSON", "converted object representation: " + listObj);

Check your logs for the output.

Done.

Leave a Reply

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