Gson 简明教程
Gson - Object Data Binding
对象数据绑定是指 JSON 与任何 JAVA 对象之间的映射。
Object data binding refers to mapping of JSON to any JAVA Object.
//Create a Gson instance
Gson gson = new Gson();
//map Student object to JSON content
String jsonString = gson.toJson(student);
//map JSON content to Student object
Student student1 = gson.fromJson(jsonString, Student.class);
Example
让我们看看对象数据绑定在实际使用中的情况。在这里,我们将直接将 JAVA 对象映射到 JSON,反之亦然。
Let’s see object data binding in action. Here we’ll map JAVA Object directly to JSON and vice versa.
在 C:\>GSON_WORKSPACE 创建一个名为 GsonTester 的 Java 类文件。
Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File - GsonTester.java
import com.google.gson.Gson;
public class GsonTester {
public static void main(String args[]) {
Gson gson = new Gson();
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
String jsonString = gson.toJson(student);
System.out.println(jsonString);
Student student1 = gson.fromJson(jsonString, Student.class);
System.out.println(student1);
}
}
class Student {
private String name;
private int age;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Student [ name: "+name+", age: "+ age+ " ]";
}
}
Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
现在运行 GsonTester 以查看结果 −
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
验证输出。
Verify the output.
{"name":"Mahesh","age":10}
Student [ name: Mahesh, age: 10 ]