@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" } }
以上是何時在Java中使用@JsonManagedReference和@JsonBackReference註解使用Jackson?的詳細內容。更多資訊請關注PHP中文網其他相關文章!