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

Tầm quan trọng của @JsonUnwrapped trong Jackson (Java)

Annotation @JsonUnwrapped dùng để "bóc tách" (unwrap) giá trị của một nested object khi serialize/deserialize, làm cho các field của nested object xuất hiện ngang hàng với field của parent class trong JSON.

Cú pháp

@Target({ANNOTATION_TYPE, FIELD, METHOD, PARAMETER})
@Retention(RUNTIME)
public @interface JsonUnwrapped

Ví dụ minh họa

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUnwrappedTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter()
                            .writeValueAsString(new Employee());
        System.out.println(json);
    }
}

class Employee {
    public int empId = 110;
    public String empName = "Raja Ramesh";
    
    @JsonUnwrapped
    public Address address = new Address();
    
    static class Address {
        public String doorNumber = "1118";
        public String street = "madhapur";
        public String pinCode = "500081";
        public String city = "Hyderabad";
    }
}

Output

{
  "empId" : 110,
  "empName" : "Raja Ramesh",
  "doorNumber" : "1118",
  "street" : "madhapur",
  "pinCode" : "500081",
  "city" : "Hyderabad"
}

Không có @JsonUnwrapped: JSON sẽ lồng object "address": { "doorNumber": "...", ... }.

Ứng dụng thực tế

  • Flatten DTO khi API yêu cầu cấu trúc phẳng.
  • Tách address, contact info thành class riêng nhưng JSON output gọn gàng.
  • Kết hợp với @JsonProperty để rename field khi unwrap.

Lưu ý

  • Có thể dùng trên field, getter, hoặc setter.
  • Nếu có conflict tên field giữa parent và nested, Jackson sẽ ném exception (cần config hoặc rename).
  • Deserialize: Jackson tự map các field phẳng ngược vào nested object.