How to convert Java object to JSON using Google Gson Tutorial

Overview

In this tutorial, we help you how to convert java object to JSON using Google Gson with Eclipse IDE

convert Java object to JSON using Google Gson


Video Tutorials



Project Structure


project structure convert object to json

Create New Project


  • Launch Eclipse IDE. 
  • Go to File-> New-> Others... Select Java Project then click Next. 
  • Type ConvertObjectToJsonGson in the "Project name" field. 
  • Click Finish.

Adding gson-2.8.2.jar lib to an Eclipse Project Folder


  • Right click this project
  • Select Bulid Path -> Configure Build Path... 
  • Under Libraries tab, click Add JARS... or Add External JARs... and give the gson-2.8.2.jar Jar
  • Click Apply
  • Click OK

Create User Class


  • Right click to the src folder, select New -> Package
  • Enter java_example in Name: field
  • Click Finish
  • Right click to the package, select New -> Class
  • Enter User in "Name:" field
  • Click Finish
  • The following code:

package java_example;

public class User {
 private String name;
 private int age;
 private String description;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}

Create ConvertObjectToJson Class


  • Right click to the package, select New -> Class
  • Enter ConvertObjectToJson in "Name:" field
  • Click Finish
  • The following code:

package java_example;

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

public class ConvertObjectToJson {

 public static void main(String[] args){
  User user = createUserData();
  
  Gson gson = new GsonBuilder()
                           .setPrettyPrinting().create();
  
  String json = gson.toJson(user);
  System.out.println(json);
 }
 
 private static User createUserData(){
  User user = new User();
  user.setName("Test");
  user.setAge(30);
  user.setDescription("Note Test");
  
  return user;
 }
}

Run & Check result


Right click to the ConvertObjectToJson class, select Run As -> Java Application

Output


{
  "name": "Test",
  "age": 30,
  "description": "Note Test"
}


Required Libraries



Previous Post
First

post written by: