首页 >Java >java教程 >何时在Java中使用@JsonManagedReference和@JsonBackReference注解使用Jackson?

何时在Java中使用@JsonManagedReference和@JsonBackReference注解使用Jackson?

WBOY
WBOY转载
2023-09-05 22:33:061124浏览

何时在Java中使用@JsonManagedReference和@JsonBackReference注解使用Jackson?

@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中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除