Gson is a library for Java that can be used to generate JSON. We can use Gson's fromJson() method to parse a JSON string into a Java object and use Gson's toJson() method to convert a Java object into a JSON string. The fromJson() method has two parameters. The first parameter is the JSON string to be parsed, and the second parameter is the Java class to be parsed. We can pass one argument to the toJson() method, which is the Java object we want to convert to a JSON string.
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
import com.google.gson.*; public class FromJsonMethodTest { public static void main(String[] args) { String jsonString = "{'id':101, 'firstName':'Jai','lastName':'Adithya'}"; <strong>Gson </strong>gson = new Gson(); Employee emp = gson.fromJson(jsonString, Employee.class); System.out.println(emp); } } // Employee class<strong> </strong>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(); } }
Id : 101, FirstName : Jai, Last Name : Adithya<strong> </strong>
public java.lang.String toJson(java.lang.Object src)
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<strong> </strong>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; } }
{"id":110,"firstName":"Raja","lastName":"Ramesh"}
The above is the detailed content of What is the difference between Gson's fromJson() and toJson() methods in Java?. For more information, please follow other related articles on the PHP Chinese website!