Converting JSON to/from Java Objects using Google GSON

This post explains converting Java object to/from JSON using Google GSON library. To get hold of Json Basics concepts, please refer to JSON basics. Let’s begin.


com.google.gson.Gson is the main class used for converting JSON to/from java objects. This class provides toJson & fromJson methods to convert Java object to/from JSON. Gson library also provides com.google.gson.GsonBuilder which is essentially a builder to create instances of Gson with additional configuration options.

Typical usages are as follows:

//Create gson instance
Gson gson = new Gson();
//or use GsonBuilder to create a Gson instance  with some additional configuration
Gson gson = new GsonBuilder().setPrettyPrinting().create();
//Convert Java object to JSON
String jsonString = gson.toJson(java_object);
//Read JSON and populate java objects
//convert JSON to Java object
Car car = gson.fromJson(jsonString, Car.class);

Complete Example

Step 1: Include Google GSON dependency in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.websystique.json</groupId>
	<artifactId>GsonObjectToJsonExample</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>GsonObjectToJsonExample</name>

	<dependencies>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3.1</version>
		</dependency>
	</dependencies>
</project>

Step 2: Create POJO

This object will be converted to and from JSON.

package com.websystique.json.gson.model;

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

public class Car {

	private String name;
	
	private int model;
	
	private double price;
	
	private List<String> colors = new ArrayList<String>();

	public String getName() {
		return name;
	}

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

	public int getModel() {
		return model;
	}

	public void setModel(int model) {
		this.model = model;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public List<String> getColors() {
		return colors;
	}

	public void setColors(List<String> colors) {
		this.colors = colors;
	}

	@Override
	public String toString() {
		return "Car [name=" + name + ", model=" + model + ", price=" + price
				+ ", colors=" + colors + "]";
	}
	
	
}

Step 3: Convert Java Object to JSON string

Convert Car object into JSON using toJson method

package com.websystique.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.websystique.json.gson.model.Car;

public class GsonObjectToJsonDemo {

	public static void main(String args[]){
		Gson gson = new Gson();
		//Gson gson = new GsonBuilder().setPrettyPrinting().create();  //Toggle comment for Pretty print JSON
		
		Car car = new Car();
		car.setName("AUDI");
		car.setModel(2014);
		car.setPrice(30000);
		
		car.getColors().add("GRAY");
		car.getColors().add("BLACK");
		car.getColors().add("WHITE");
	 
		String jsonString = gson.toJson(car); // Convert car object to JSON string
		System.out.println(jsonString);
	}
}

Run above program. Following is the output

{"name":"AUDI","model":2014,"price":30000.0,"colors":["GRAY","BLACK","WHITE"]}

Pretty print JSON

You can pretty print JSON using GsonBuilder setPrettyPrinting. Just toggle the comment above, following is the output.

{
  "name": "AUDI",
  "model": 2014,
  "price": 30000.0,
  "colors": [
    "GRAY",
    "BLACK",
    "WHITE"
  ]
}

Step 4: Convert JSON string to Java Object

Convert JSON string to Car object using fromJson method

package com.websystique.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.websystique.json.gson.model.Car;

public class GsonObjectToJsonDemo {

	public static void main(String args[]){
		Gson gson = new Gson();
		//Gson gson = new GsonBuilder().setPrettyPrinting().create();  //Toggle comment for Pretty print JSON
		
		String jsonString  = "{\"name\":\"AUDI\",\"model\":2014, \"price\":30000,\"colors\":[\"GRAY\",\"BLACK\",\"WHITE\"]}";
	
		Car car = gson.fromJson(jsonString, Car.class);// Convert JSON String to car object
		System.out.println(car);
	}
}

Run above program. Following is the output

Car [name=AUDI, model=2014, price=30000.0, colors=[GRAY, BLACK, WHITE]]

That’s it. In the next post we will learn how Json can be represented as a conceptual Tree.

References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?