Jun 152016

ADM

How to convert object to / from JSON using Gson

  • 15 June 2016
  • ADM

 

 

 

How to convert object to / from JSON using Gson - images/logos/java.jpg

 

Here is a simple example of converting objects into JSON strings and back using Gson.

Dependencies

Download and add the jar file as dependency for your project.

For Maven users add the Gson dependency in your pom.xml file

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.6.2</version>
</dependency>

Example

For this tutorials I will use 2 POJO classes: User and Permission and one class as test.

One simple class: Permission.java

package com.admfactory.gson;

public class Permission {
	private String name;
	
	public Permission(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

User.java will use Permission.java as embedded object.

package com.admfactory.gson;

import java.util.ArrayList;
import java.util.List;

public class User {
	private String username;
	private String email;
	private String password;
	private List<Permission> permissions;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getEmail() {
		return email;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public List<Permission> getPermissions() {
		return permissions;
	}
	
	public void setPermissions(List<Permission> permissions) {
		this.permissions = permissions;
	}
	
	/**
	 * Method used to add a permission to the array. 
	 *
	 * @param p {@link Permission} object
	 */
	public void addPermission(Permission p) {
		/** Check if the array is null, if yes create a new array */
		if (this.permissions == null)
			this.permissions = new ArrayList<Permission>();
		this.permissions.add(p);
	}
}

GsonTest.java used as test class.

package com.admfactory.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonTest {
	
	public static void main(String[] args) {
		/** Create the gson builder object */
		 GsonBuilder builder = new GsonBuilder();
       Gson gson = builder.create();
       
       System.out.println("Object to JSON String Test");
       
       /** Create a user object */
       User user = new User();
       user.setUsername("johndoe");
       user.setEmail("john.doe@admfactory.com");
       user.setPassword("a1234");
       
       /** Add some permission objects as embedded objects */
       Permission p1 = new Permission("add.user");
       Permission p2 = new Permission("delete.user");
       Permission p3 = new Permission("modify.user");
       
       user.addPermission(p1);
       user.addPermission(p2);
       user.addPermission(p3);
       
       /** Get the string from the object and print it on the console */
       String string = gson.toJson(user);
       System.out.println("JSON String: " + string);
       
       System.out.println();
       System.out.println("JSON String to Object Test");
       
       /** Use the string printed to create a new object */
       User u = gson.fromJson(string, User.class);
       
       /** Print one variable to the console */
       System.out.println("Username : " + u.getUsername());
       
       /** Print one embedded variable to the console */
       System.out.println("First permission: " + u.getPermissions().get(0).getName());
	}
}

For more details please follow the comments from the source code.

Output

Object to JSON String Test
JSON String: {"username":"johndoe","email":"john.doe@admfactory.com","password":"a1234","permissions":[{"name":"add.user"},{"name":"delete.user"},{"name":"modify.user"}]}

JSON String to Object Test
Username : johndoe
First permission: add.user

Conclusions

As you can see the string output is on a single line. If you need to have a pretty print for your json string replace the Gson object creating line from

/** Create the gson builder object */
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();

to

/** Create the gson builder object */
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.setPrettyPrinting().create();

And now the output will be in a human readable format.

JSON String: {
  "username": "johndoe",
  "email": "john.doe@admfactory.com",
  "password": "a1234",
  "permissions": [
    {
      "name": "add.user"
    },
    {
      "name": "delete.user"
    },
    {
      "name": "modify.user"
    }
  ]
}

 

 

 

References