Gson物件資料系結


物件資料系結是指將JSON對映到任何JAVA物件。

//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);

範例

讓我們看看物件資料系結的行動。 這裡將JAVA物件直接對映到JSON,反之亦然。參考實現程式碼: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(26); 
      student.setName("Maxsu"); 

      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+ " ]"; 
   }  
}

執行上面範例程式碼,得到以下結果 -

{"name":"Maxsu","age":26} 
Student [ name: Maxsu, age: 26 ]