Annotation @Until ngược với @Since: field chỉ serialize khi version hiện tại **< version chỉ định**. Dùng để **loại bỏ field cũ** (deprecate) trong các version mới.
Cú pháp
@Documented @Retention(RUNTIME) @Target({FIELD, TYPE})
public @interface Until {
double value();
}
Ví dụ minh họa
import com.google.gson.annotations.Until;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonUntilTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeName("Adithya");
emp.setEmployeeId(115);
emp.setEmployeeTechnology("Python");
emp.setEmploeeAddress("Pune");
// Version 0.5 - tất cả field (empTech, empAddress có @Until(1.1) > 0.5)
Gson gson = new GsonBuilder().setPrettyPrinting().setVersion(0.5).create();
System.out.println("Version 0.5:\n" + gson.toJson(emp));
// Version 1.0 - vẫn có empTech, empAddress
gson = new GsonBuilder().setPrettyPrinting().setVersion(1.0).create();
System.out.println("Version 1.0:\n" + gson.toJson(emp));
// Version 1.1 - empTech, empAddress bị LOẠI BỎ (version >= 1.1)
gson = new GsonBuilder().setPrettyPrinting().setVersion(1.1).create();
System.out.println("Version 1.1:\n" + gson.toJson(emp));
}
}
class Employee {
private String empName;
private int empId;
@Until(1.1)
private String empTech;
@Until(1.1)
private String empAddress;
// getters/setters...
}
Output
Version 0.5:
{
"empName": "Adithya",
"empId": 115,
"empTech": "Python",
"empAddress": "Pune"
}
Version 1.0:
{
"empName": "Adithya",
"empId": 115,
"empTech": "Python",
"empAddress": "Pune"
}
Version 1.1:
{
"empName": "Adithya",
"empId": 115
}
Kết hợp @Since và @Until
class Employee {
// Field chỉ tồn tại từ version 1.0 đến trước 2.0
@Since(1.0) @Until(2.0)
private String temporaryField;
// Field mới từ version 2.0
@Since(2.0)
private String newField;
}
Use case thực tế
- **Deprecation lifecycle**: Field mới @Since(2.0), field cũ @Until(2.0) - chuyển đổi mượt mà.
- **A/B testing**: Bật/tắt field theo version client.
- **Mobile API**: App version cũ không nhận field mới, app mới nhận đầy đủ.
Lưu ý
- @Until chỉ ảnh hưởng **serialize**. Deserialize: field bị bỏ qua nếu version cao hơn.
- Cần quản lý version cẩn thận tránh conflict giữa @Since/@Until.
- Gson 2.10+: Hỗ trợ tốt hơn cho versioning phức tạp.