The Gson ไลบรารีให้ระบบการกำหนดเวอร์ชัน .ที่เรียบง่าย สำหรับอ็อบเจ็กต์ Java ที่อ่านและเขียน และยังมีคำอธิบายประกอบชื่อ @Since สำหรับแนวคิดการกำหนดเวอร์ชัน @Since(versionnumber) .
เราสามารถสร้างอินสแตนซ์ Gson ด้วยการกำหนดเวอร์ชันโดยใช้ GsonBuilder().setVersion() กระบวนการ. ถ้าเราพูดถึงเช่น setVersion(2.0), หมายความว่าทุกช่องที่มี 2.0 หรือน้อยกว่ามีสิทธิ์แยกวิเคราะห์
ไวยากรณ์
public GsonBuilder setVersion(double ignoreVersionsAfter)
ตัวอย่าง
import com.google.gson.*;
import com.google.gson.annotations.*;
public class VersionSupportTest {
public static void main(String[] args) {
Person person = new Person();
person.firstName = "Raja";
person.lastName = "Ramesh";
Gson gson1 = new GsonBuilder().setVersion(1.0).setPrettyPrinting().create();
System.out.println("Version 1.0:");
System.out.println(gson1.toJson(person));
Gson gson2 = new GsonBuilder().setVersion(2.0).setPrettyPrinting().create();
System.out.println("Version 2.0:");
System.out.println(gson2.toJson(person));
}
}
// Person class
class Person {
@Since(1.0)
public String firstName;
@Since(2.0)
public String lastName;
} ผลลัพธ์
Version 1.0:
{
"firstName": "Raja"
}
Version 2.0:
{
"firstName": "Raja",
"lastName": "Ramesh"
}