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

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

Annotation @JsonRootName bọc (wrap) object gốc trong một wrapper object với tên chỉ định. Cần bật feature SerializationFeature.WRAP_ROOT_VALUE.

Ví dụ minh họa

import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonRootNameTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        // BẬT feature WRAP_ROOT_VALUE
        String json = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE)
                            .writeValueAsString(new Employee());
        System.out.println(json);
    }
}

@JsonRootName(value = "user")
class Employee {
    public int empId = 125;
    public String empName = "Raja Ramesh";
}

Output

{"user":{"empId":125,"empName":"Raja Ramesh"}}

Không bật WRAP_ROOT_VALUE: {"empId":125,"empName":"Raja Ramesh"} (bỏ qua @JsonRootName).

Khi nào dùng?

  • API yêu cầu root wrapper (VD: một số REST API legacy, XML-to-JSON mapping).
  • Phân biệt type khi deserialize polymorphic collections.
  • Tuân thủ JSON API spec (như JSON:API spec khuyến nghị root object).

Deserialize với Root Name

// Cần bật DeserializationFeature.UNWRAP_ROOT_VALUE
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
Employee emp = mapper.readValue(jsonString, Employee.class);

Lưu ý

  • Có thể đặt @JsonRootName trên class hoặc getter.
  • Namespace: com.fasterxml.jackson.annotation.JsonRootName.
  • Không hoạt động nếu không enable feature WRAP_ROOT_VALUE/UNWRAP_ROOT_VALUE.