Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Sử dụng @Since annotation với Gson (Java)

Annotation @Since kết hợp với GsonBuilder.setVersion() để **versioning field** khi serialize. Field chỉ xuất hiện trong JSON khi version hiện tại >= version của field.

Cú pháp

@Documented @Retention(RUNTIME) @Target({FIELD, TYPE})
public @interface Since {
    double value();
}

Ví dụ minh họa

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

public class GsonSinceTest {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setEmployeeName("Raja Ramesh");
        emp.setEmployeeId(125);
        emp.setEmployeeTechnology("Java");
        emp.setEmploeeAddress("Hyderabad");
        
        // Version 0.5 - chỉ field không có @Since hoặc @Since <= 0.5
        Gson gson = new GsonBuilder().setPrettyPrinting().setVersion(0.5).create();
        System.out.println("Version 0.5:\n" + gson.toJson(emp));
        
        // Version 1.0 - thêm empTech (@Since(1.0))
        gson = new GsonBuilder().setPrettyPrinting().setVersion(1.0).create();
        System.out.println("Version 1.0:\n" + gson.toJson(emp));
        
        // Version 1.1 - thêm empAddress (@Since(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;
    
    @Since(1.0)
    private String empTech;
    
    @Since(1.1)
    private String empAddress;
    // getters/setters...
}

Output

Version 0.5:
{
  "empName": "Raja Ramesh",
  "empId": 125
}

Version 1.0:
{
  "empName": "Raja Ramesh",
  "empId": 125,
  "empTech": "Java"
}

Version 1.1:
{
  "empName": "Raja Ramesh",
  "empId": 125,
  "empTech": "Java",
  "empAddress": "Hyderabad"
}

Ứng dụng thực tế

  • **API Versioning**: Client cũ (version thấp) nhận ít field hơn, client mới nhận full field.
  • **Backward compatibility**: Thêm field mới với @Since version cao hơn, không break client cũ.
  • **Deprecation**: Kết hợp với @Until để loại bỏ field cũ.

Lưu ý

  • @Since áp dụng cho **serialize**. Deserialize: Gson bỏ qua field không khớp version (nếu config lenient).
  • Version type là double - có thể dùng 1.0, 1.1, 2.0...
  • Có thể áp dụng ở **class level** để versioning toàn bộ type.