何时在java中使用@jsonmanagedreference和@jsonbackreference注解使用jackson?-kb88凯时官网登录

时间:2023-09-06
阅读:
免费资源网 - https://freexyz.cn/

@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 list;
   public backreferencebeantest(int empid, string empname) {
      this.empid = empid;
      this.empname = empname;
      list = new arraylist();
   }
   public void addemployees(managedreferencebeantest managedreferencebeantest) {
      list.add(managedreferencebeantest);
   }
}

输出

{
   "empid" : 135,
   "empname" : "adithya ram",
   "manager" : {
      "empid" : 110,
      "empname" : "sai chaitanya"
   }
}

以上就是何时在java中使用@jsonmanagedreference和@jsonbackreference注解使用jackson?的详细内容。

免费资源网 - https://freexyz.cn/
返回顶部
顶部
网站地图