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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books