Heim >Java >javaLernprogramm >Was ist der Unterschied zwischen den Methoden fromJson() und toJson() von Gson in Java?
Gson是一个用于Java的库,可以用来生成JSON。我们可以使用Gson的fromJson()方法将JSON字符串解析为Java对象,并使用Gson的toJson()方法将Java对象转换为JSON字符串。fromJson()方法有两个参数,第一个参数是要解析的JSON字符串,第二个参数是要解析的Java类。我们可以将一个参数传递给toJson()方法,即我们要转换为JSON字符串的Java对象。
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"}
Das obige ist der detaillierte Inhalt vonWas ist der Unterschied zwischen den Methoden fromJson() und toJson() von Gson in Java?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!