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 Object直接映射到JSON,反之亦然。

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

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

验证结果

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

C:\GSON_WORKSPACE>javac GsonTester.java

现在运行 GsonTester 查看结果 -

C:\GSON_WORKSPACE>java GsonTester

验证输出。

{"name":"Mahesh","age":10}
Student [ name: Mahesh, age: 10 ]