Android Library: Gson (Usage and Example)


Serialization

Serialization is a process of writing the state of an object into a byte stream. Similarly, deserialization is the process of turning the byte stream into an object.

Installation

You can get the latest version of Gson library from here.
Right now the latest version is 2.7. Click on the version from the link and you will get the instruction to add the library for your favorite build system.

For Gradle, I would use,

compile group: 'com.google.code.gson', name: 'gson', version: '2.7'

this can be simplified to,

compile "com.google.code.gson:gson:2.7"

Example#1

We have a class named User

public class User {

    private String firstName;

    private String lastName;

    private int age;

    private List<String> emails;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getEmails() {
        return emails;
    }

    public void setEmails(List<String> emails) {
        this.emails = emails;
    }
}

Now let’s create an object of class User and convert the object to String and after that we will create an User object from the String.


User user = new User();
user.setFirstName("Android");
user.setLastName("Studio");
user.setAge(3);
user.setEmails(Arrays.asList("android.studio@gmail.com", "android.studio@android.com"));

// converting the User object to string
Gson gson = new Gson();
String jsonStringUser = gson.toJson(user, User.class);

// Creating the User object from string
User returnedUser = gson.fromJson(jsonStringUser, User.class);

Example#2

Now, suppose, we have a generic class.

public class Employee<T> {

	private T person;

	public T getPerson() {
		return person;
	}

	public void setPerson(T person) {
		this.person = person;
	}
}

Now let’s create an object of class Employee and convert the object to String and after that we will create an Employee object from the String.

User user = new User();
user.setFirstName("Android");
user.setLastName("Studio");
user.setAge(3);
user.setEmails(Arrays.asList("android.studio@gmail.com", "android.studio@android.com"));

Employee<User> employee = new Employee<>();
employee.setPerson(user);

Gson gson = new Gson();

// This will not work
String jsonString = gson.toJson(employee, Employee.class);

We could have put any class object inside Employee. There is no way the JVM will know the object type until runtime. There is a concept of Java type erasure that will explain why the simple Employee.class will not work with Gson. To resolve the issue we need to get the type at runtime using TypeToken

User user = new User();
user.setFirstName("Android");
user.setLastName("Studio");
user.setAge(3);
user.setEmails(Arrays.asList("android.studio@gmail.com", "android.studio@android.com"));

Employee<User> employee = new Employee<>();
employee.setPerson(user);

Gson gson = new Gson();

Type type = new TypeToken<Employee<User>>() {
}.getType();

String jsonString = gson.toJson(employee, type);

// load the value
Employee<User> returnedEmployee = gson.fromJson(jsonString, type);
User returnedUser = returnedEmployee.getPerson();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s