Differences Between fromJson and toJson Methods of Gson in Java



Gson is a Java library which is developed by Google and used to convert Java objects into JSON and vice versa. It is mostly used in applications where data can be exchanged in JSON format.

There are two useful methods in Gson that we are going to discuss in this article. These methods are fromJson() and toJson().

The fromJson() Method

The fromJson() method is used to convert a JSON string into a Java object. It takes two parameters: the JSON string and the class type of the object you want to create. Here is the syntax of the fromJson() method:

gson.fromJson(json, Person.class);

The toJson() Method

The toJson() method is used to convert a Java object into a JSON string. It takes one parameter: the Java object you want to convert. Here is the syntax of the toJson() method:

gson.toJson(person);

Difference Between fromJson() & toJson()

Here are the main differences between the fromJson() and toJson() methods:

fromJson() toJson()
The fromJson() method is used to convert a JSON string into a Java object. The toJson() method is used to convert a Java object into a JSON string.
It takes two parameters: the JSON string and the class type of the object you want to create. It takes one parameter: the Java object you want to convert.
Returns a Java object. Returns a JSON string.
It is used for deserialization. It is used for serialization.
It is used to read data from a JSON string. It is used for writing data to a JSON string.
It is used for parsing JSON data. It is used to generate JSON data.

Example 1

Here is an example of how to use the fromJson() to convert a JSON string into a Java object.

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.List;

public class Main {
   public static void main(String[] args) {
      Gson gson = new Gson();
      String json = "{"name":"Aish", "age":22, "city":"Mumbai"}";
      Person person = gson.fromJson(json, Person.class);
      System.out.println(person);
   }
}

Output

Following is the output of the above program:

Person{name='Aish', age=22, city='Mumbai'}

Example 2

Here is an example of how to use the toJson() method to convert a Java object into a JSON string.

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class Main {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Person person = new Person("Aish", 22, "Mumbai");
      String json = gson.toJson(person);
      System.out.println(json);
   }
}

Output

Following is the output of the above program:

{"name":"Aish","age":22,"city":"Mumbai"}
Updated on: 2025-05-13T16:23:07+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements