Gson 对象序列化

让我们将 Java 对象序列化为Json文件,然后读取该 Json 文件以获取该对象。在这个例子中,我们创建了一个 Student 类。我们将创建一个 student.json 文件,该文件将具有 Student 对象的 json 表示。

 

1. 范例

C:\>GSON_WORKSPACE中创建名为 GsonTester 的Java类文件。

文件:GsonTester.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;  

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;  

public class GsonTester {
   public static void main(String args[]) {
      GsonTester tester = new GsonTester();
      try {
         Student student = new Student();
         student.setAge(10);
         student.setName("Mahesh");
         tester.writeJSON(student);  
         Student student1 = tester.readJSON();
         System.out.println(student1);
      }
      catch(FileNotFoundException e) {
         e.printStackTrace();
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
   private void writeJSON(Student student) throws IOException {
      GsonBuilder builder = new GsonBuilder();
      Gson gson = builder.create();
      FileWriter writer = new FileWriter("student.json");   
      writer.write(gson.toJson(student));   
      writer.close();
   }  
   private Student readJSON() throws FileNotFoundException {
      GsonBuilder builder = new GsonBuilder();
      Gson gson = builder.create();
      BufferedReader bufferedReader = new BufferedReader(
         new FileReader("student.json"));   

      Student student = gson.fromJson(bufferedReader, Student.class);
      return student;
   }
}
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+ " ]";
   }  
}

 

2. 验证结果

使用 javac 编译器编译类如下 -

C:\GSON_WORKSPACE>javac GsonTester.java

现在运行GsonTester查看结果 -

C:\GSON_WORKSPACE>java GsonTester

验证输出

Student [ name: Mahesh, age: 10 ]

Data Binding API用于使用属性访问器或使用注释将 JSON 转换为 POJO(Plain Old Java Object)和从 POJO(PlainOld Java Object)转换 JSON。它有两种类 ...