gson

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.

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button