@JsonManagedReference 및 @JsonBackReference 주석 양방향 JSON 구조를 만드는 데 사용할 수 있습니다. 방법. @JsonManagedReference 주석은 정방향 참조입니다. 직렬화 프로세스 중에 포함되는 반면 @JsonBackReference 주석은 역참조 입니다. 직렬화 과정에서 생략됩니다.
아래 예에서 @JsonManagedReference 및 @JsonBackReference 주석을 구현할 수 있습니다.
예
import java.util.*; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; public class ManagedReferenceBackReferenceTest { public static void main(String args[]) throws JsonProcessingException { BackReferenceBeanTest testBean = new BackReferenceBeanTest(110, "Sai Chaitanya"); ManagedReferenceBeanTest bean = new ManagedReferenceBeanTest(135, "Adithya Ram", testBean); testBean.addEmployees(bean); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean); System.out.println(jsonString); } } class ManagedReferenceBeanTest { public int empId = 115; public String empName = "Raja Ramesh"; @JsonManagedReference public BackReferenceBeanTest manager; public ManagedReferenceBeanTest(int empId, String empName, BackReferenceBeanTest manager) { this.empId = empId; this.empName = empName; this.manager = manager; } } class BackReferenceBeanTest { public int empId = 125; public String empName = "Jai Dev"; @JsonBackReference public List<ManagedReferenceBeanTest> list; public BackReferenceBeanTest(int empId, String empName) { this.empId = empId; this.empName = empName; list = new ArrayList<ManagedReferenceBeanTest>(); } public void addEmployees(ManagedReferenceBeanTest managedReferenceBeanTest) { list.add(managedReferenceBeanTest); } }
출력
{ "empId" : 135, "empName" : "Adithya Ram", "manager" : { "empId" : 110, "empName" : "Sai Chaitanya" } }