java – 为什么Jackson的PropertyGenerator会阻止递归循环
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 为什么Jackson的PropertyGenerator会阻止递归循环,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2289字,纯文字阅读大概需要4分钟。
内容图文
![java – 为什么Jackson的PropertyGenerator会阻止递归循环](/upload/InfoBanner/zyjiaocheng/795/f149e06fb8aa467c8e17755c713a699c.jpg)
我有两个双向映射的实体.一种具有注册集合和注册本身的车辆.这些实体作为REST服务公开.
@Entity
@XmlRootElement
public class Vehicle implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String brand;
private String type;
@OneToMany(mappedBy = "vehicle", fetch = FetchType.EAGER)
private List<Registration> registrations;
}
问题是FetchType.EAGER产生无限递归.
@Entity
@XmlRootElement
public class Registration implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
private Vehicle vehicle;
}
经过一些研究,我发现我必须将注释@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =“id”)添加到Vehicle类来解决问题.
我的问题是:PropertyGenerator类实际上做了什么?
解决方法:
问题不在于FetchType.EAGER. FetchType.EAGER是JPA注释,在使用Jackson序列化Vehicle实例时不会发挥作用.
实际上发生的事情是杰克逊正在序列化一个车辆,该车辆触发了登记列表的序列化,该车辆序列化车辆,其具有登记列表,等等.
正如您所注意到的,@ JsonIdentityInfo注释会使无限递归短路,但这并不是因为您指定了特定的PropertyGenerator. @JsonIdentityInfo的JavaDoc可以让您深入了解正在发生的事情:
@JsonIdentityInfo Annotation used for indicating that values of annotated type or property should be serializing so that instances either contain additional object identifier (in addition actual object properties), or as a reference that consists of an object id that refers to a full serialization. In practice this is done by serializing the first instance as full object and object identity, and other references to the object as reference values.
换句话说,第一次序列化时,您将获得完整的序列化JSON / XML版本.下次该对象被序列化时,您将获得对该第一个序列化对象的引用.
还有其他方法可以解决这个问题.查看Infinite Recursion with Jackson JSON and Hibernate JPA issue(您的问题可以说是这个问题的副本).这里的答案建议您也可以使用@JsonIgnore或@JsonManagedReference和@JsonBackReference的组合来避免无限递归.
现在,针对您关于PropertyGenerator实际执行的操作的具体问题:它指示Jackson使用您类中的特定属性作为对象的完整序列化版本的引用.您将“id”指定为属性,因此在生成的序列化JSON / XML中,您应该看到如果您有一个ID为342的对象,那么第一个序列化对象将显示id和所有其他序列化属性,但每次后续该对象都是序列化你只会看到342序列化作为对原始对象的引用.
内容总结
以上是互联网集市为您收集整理的java – 为什么Jackson的PropertyGenerator会阻止递归循环全部内容,希望文章能够帮你解决java – 为什么Jackson的PropertyGenerator会阻止递归循环所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。