Differences between fromJson() and toJson() methods of Gson in Java?

JavaJSONObject Oriented ProgrammingProgramming

A Gson is a library for java and it can be used to generate a JSON. We can use the fromJson() method of Gson to parse JSON string into java object and use the toJson() method of Gson to convert Java objects into JSON string. There are two parameters in the fromJson() method, the first parameter is JSON String which we want to parse and the second parameter is Java class to parse JSON string. We can pass one parameter into the toJson() method is the Java object which we want to convert into a JSON string.

Syntax for fromJson()

public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException

Example

import com.google.gson.*;
public class FromJsonMethodTest {
   public static void main(String[] args) {
      String jsonString = "{'id':101, 'firstName':'Jai','lastName':'Adithya'}";
      Gson gson = new Gson();
      Employee emp = gson.fromJson(jsonString, Employee.class);
      System.out.println(emp);
   }
}
// Employee class
class Employee {
   private int id;
   private String firstName;
   private String lastName;
   public Employee() {}
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   @Override
   public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append("Id : " + id);
      sb.append(", FirstName : " + firstName);
      sb.append(", Last Name : " + lastName);
      return sb.toString();
   }
}

Output

Id : 101, FirstName : Jai, Last Name : Adithya


Syntax for toJson()

public java.lang.String toJson(java.lang.Object src)

Example

import com.google.gson.*;
public class ToJsonMethodTest {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.setId(110);
      emp.setFirstName("Raja");
      emp.setLastName("Ramesh");
      Gson gson = new Gson();
      String jsonString = gson.toJson(emp);
      System.out.println(jsonString);
   }
}
// Employee class
class Employee {
   private int id;
   private String firstName;
   private String lastName;
   public Employee() {}
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
}

Output

{"id":110,"firstName":"Raja","lastName":"Ramesh"}
raja
Published on 03-Oct-2019 08:03:52
Advertisements