Convert Java object to JSON string

In this tutorial, we will learn about how to convert Java object to JSON string in Java. Before starting with this tutorial we should know about the basics of  JSON.

Java object to JSON string

Let’s first know about what are objects in java –

An object in Java is an instance of a java class where each object has its identity, behavior, and state. Here the state of an object is stored in variables or fields and functions or methods display the object’s behavior.

Now let’s brief about JSON string –

The context surrounded by single or double quotes is known as JSON strings.

task 5 a

There are the following methods that can be used –

  • JACKSON API
  • GSON

Here we will use the GSON method which is an open-source Java library that is used to serialize and vice versa.

Steps to perform this task

  1. Add the jar file GSON
  2. Make a POJO (plain old java object) code.
  3. Code for conversion.

CODE

POJO code 

import com.google.gson.Gson;

public class EmployeeData {
    //lets assign some values in the class
    private int id = 101;
    private String name = "RAM";
    private String gender = "MALE";
    private String company = "Codespeedy";
    private int salary= 40000;
    
}

Explanation

  • In this java class we are assigning values to objects.

Object to json string conversion code

import com.google.gson.Gson;

public class JavaToJsonMain {

    public static void main(String[] args) {
       
        EmployeeData emp = new EmployeeData();
       
        Gson gson = new Gson();
  
   //this method serializes the specified object into its equivalent Json representation.
   
   String jsonEmployeeData = gson.toJson(emp);
   
              String[] sArray = jsonEmployeeData.split(",");
        for(String x:sArray)
            System.out.println(x);
    }
}

Explanation

In this java class we are-

  • Creating an instance of the EmplyeeData  POJO.
  • Creating an instance of Gson.

OUTPUT

Leave a Reply

Your email address will not be published.