Gson 简明教程

Gson - Versioning Support

Gson 提供 @Since 注释来控制基于其不同版本的类的 Json 序列化/反序列化。考虑具有版本支持的以下类。在此类中,我们最初定义了两个变量 rollNoname ,然后我们在后面将 verified 添加为一个新变量。使用 @Since,我们定义了 rollNoname 为版本 1.0,并验证为版本 1.1。

Gson provides @Since annotation to control the Json serialization/deserialization of a class based on its various versions. Consider the following class with versioning support. In this class, we’ve initially defined two variables rollNo and name and later on, we added verified as a new variable. Using @Since, we’ve defined rollNo and name as of version 1.0 and verified to be of version 1.1.

class Student {
   @Since(1.0)
   private int rollNo;

   @Since(1.0)
   private String name;

   @Since(1.1)
   private boolean verified;
}

GsonBuilder 提供 setVersion() 方法来序列化此类版本化类。

GsonBuilder provides the setVersion() method to serialize such versioned class.

GsonBuilder builder = new GsonBuilder();
builder.setVersion(1.0);
Gson gson = builder.create();

Example

让我们看一个版本支持的示例。在 C:\>GSON_WORKSPACE 中创建一个名为 GsonTester 的 Java 类文件。

Let’s see an example of versioning support in action. Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.

File - GsonTester.java

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

public class GsonTester {
   public static void main(String args[]) {

      GsonBuilder builder = new GsonBuilder();
      builder.setVersion(1.0);
      Gson gson = builder.create();

      Student student = new Student();
      student.setRollNo(1);
      student.setName("Mahesh Kumar");
      student.setVerified(true);

      String jsonString = gson.toJson(student);
      System.out.println(jsonString);

      gson = new Gson();
      jsonString = gson.toJson(student);
      System.out.println(jsonString);
   }
}

class Student {
   @Since(1.0)
   private int rollNo;

   @Since(1.0)
   private String name;

   @Since(1.1)
   private boolean verified;

   public int getRollNo() {
      return rollNo;
   }

   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public void setVerified(boolean verified) {
      this.verified = verified;
   }

   public boolean isVerified() {
      return verified;
   }
}

Verify the result

使用以下 javac 编译器编译类:

Compile the classes using javac compiler as follows −

C:\GSON_WORKSPACE>javac GsonTester.java

现在运行 GsonTester 来查看结果 −

Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

验证输出。

Verify the output.

{"rollNo":1,"name":"Mahesh Kumar"}
{"rollNo":1,"name":"Mahesh Kumar","verified":true}