Gson 对象序列化

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 ]

下一节:gson 数据绑定

gson 教程

相关文章