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

Cách định nghĩa tên thay thế (alias) cho field dùng Jackson trong Java

Annotation @JsonAlias cho phép định nghĩa một hoặc nhiều tên thay thế cho thuộc tính khi deserialize (JSON → Java object). Khi serialize (Java → JSON), chỉ dùng tên property gốc.

Cú pháp

@Target({ANNOTATION_TYPE, FIELD, METHOD, PARAMETER})
@Retention(RUNTIME)
public @interface JsonAlias {
    String[] value();
}

Ví dụ minh họa

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;

public class JsonAliasExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // JSON input dùng alias "ename" thay cho "empName"
        String json = "{ \"empId\": 110, \"ename\": \"Raja\", \"empTechnology\": { \"skill\": \"Java\", \"mySubSkill\": \"Oracle\" } }";
        
        Employee emp = mapper.readValue(json, Employee.class);
        System.out.println("Deserialized: " + emp);
        
        // Serialize lại -> dùng tên gốc
        String output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
        System.out.println("Serialized:\n" + output);
    }
}

class Technology {
    @JsonProperty("skill")
    private String skill;
    
    @JsonProperty("subSkill")
    @JsonAlias({"sSkill", "mySubSkill"}) // Aliases cho deserialize
    private String subSkill;
    
    // getters/setters...
}

class Employee {
    @JsonProperty("empId")
    private Integer id;
    
    @JsonProperty("empName")
    @JsonAlias({"ename", "myename"}) // Aliases
    private String name;
    
    @JsonProperty("empTechnology")
    private Technology tech;
    
    // getters/setters...
}

Kết quả

Deserialized: Employee{id=110, name='Raja', tech=Technology{skill='Java', subSkill='Oralce'}}
Serialized:
{
  "empId" : 110,
  "empName" : "Raja",
  "empTechnology" : {
    "skill" : "Java",
    "subSkill" : "Oracle"
  }
}

Tóm tắt:

  • @JsonProperty("tên_json"): Đổi tên field khi CẢ serialize VÀ deserialize.
  • @JsonAlias({"alias1", "alias2"}): Chỉ dùng khi DESERIALIZE (đọc JSON). Serialize vẫn dùng tên property/@JsonProperty.