黄色电影一区二区,韩国少妇自慰A片免费看,精品人妻少妇一级毛片免费蜜桃AV按摩师 ,超碰 香蕉

Gson 對象序列化

gson 對象序列化

讓我們將 java 對象序列化為json文件,然后讀取該 json 文件以獲取該對象。在這個例子中,我們創(chuàng)建了一個 student 類。我們將創(chuàng)建一個 student.json 文件,該文件將具有 student 對象的 json 表示。

 

1. 范例

在 c:\>gson_workspace中創(chuàng)建名為 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. 驗證結(jié)果

使用 javac 編譯器編譯類如下 -

c:\gson_workspace>javac gsontester.java

現(xiàn)在運行g(shù)sontester查看結(jié)果 -

c:\gson_workspace>java gsontester

驗證輸出

student [ name: mahesh, age: 10 ]

下一節(jié):gson 數(shù)據(jù)綁定

gson 教程

相關(guān)文章