Computer >> Máy Tính >  >> Lập trình >> Java

Tầm quan trọng của chú thích @JsonRootName bằng cách sử dụng Jackson trong Java?

@JsonRootName chú thích có thể được sử dụng để bọc một đối tượng để tuần tự hóa với một phần tử cấp cao nhất. Chúng tôi có thể chuyển tên dưới dạng tham số cho @JsonRootName chú thích. Chúng tôi có thể sử dụng " WRAP_ROOT_VALUE" tính năng của SerializationFeature enum có thể được kích hoạt để tạo giá trị gốc được bao bọc trong một đối tượng JSON thuộc tính duy nhất trong đó khóa là tên gốc.

Ví dụ

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

public class JsonRootNameAnnotationTest {
   public static void main(String args[]) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(new Employee());
      System.out.println(jsonString);
   }
}

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

Đầu ra

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