Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Convert Java Object To / From JSON using Gson example

In this example we are going to see how to use Gson Java library in order to convert a Java object from / to JSON. You will notice that the GSON API is very easy and straight forward to use in contrast with other JSON parsers.
 
 
 
 
 
 
 
 

1. Gson dependencies

If you are using Maven in your project you just have to add the following dependencies in pom.xml:

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

If you’re not using Maven you have to download the library from the official site of Gson Project and add the jars to your build path.

2. Java class for the demo

This is the class that we are going to use in order to demonstrate the from / to JSON conversions.

student.java:

package com.javacodegeeks.java.core;

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

public class Student {

	private int id;
	private String firstName;
	private String lastName;
	private int age;

	private List<String> list ;

	public Student(String fname, String lname, int age, int id) {

		this.firstName = fname;
		this.lastName = lname;
		this.age = age;
		this.id = id;

		this.list = new ArrayList<String>();
		this.list.add("Str1");
		this.list.add("Str2");
		this.list.add("Str3");

	}

	public void setFirstName(String fname) {
		this.firstName = fname;
	}

	public String getFirstName() {
		return this.firstName;
	}

	public void setLastName(String lname) {
		this.lastName = lname;
	}

	public String getLastName() {
		return this.lastName;
	}

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

	public int getAge() {
		return this.age;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return this.id;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.firstName)
				.append(" Last Name : ").append(this.lastName)
				.append(" Age : ").append(this.age).append(" ID : ")
				.append(this.id).append(" "+this.list).toString();
	}
}

3. Convert an Objet to Json representation

JSONGsonExample.java:

package com.javacodegeeks.java.core;

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

public class JSONGsonExample {

	private static final String jsonFilePath="C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		Student student = new Student("Jack", "James",10,10);

		Gson gson = new Gson();

		String jsonRepresentation = gson.toJson(student);

		try {

			FileWriter Filewriter = new FileWriter(jsonFilePath);
			Filewriter.write(jsonRepresentation);
			Filewriter.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println(jsonRepresentation);

	}
}

jsonFile.json:

{"id":10,"firstName":"Jack","lastName":"James","age":10,"list":["Str1","Str2","Str3"]}

3. Convert a Json representation to a Java object

package com.javacodegeeks.java.core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class JSONGsonExample {

	private static final String jsonFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		Gson gson = new Gson();

		try {

			FileReader fileReader = new FileReader(jsonFilePath);

			BufferedReader buffered = new BufferedReader(fileReader);

			Student obj = gson.fromJson(buffered, Student.class);

			System.out.println(obj);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

output:

 First Name : Jack Last Name : James Age : 10 ID : 10 [Str1, Str2, Str3]

 
This was an example on how to convert Java Object To / From JSON using Gson example.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close