杰克逊注释不起作用

时间:2017-07-20 07:15:58

标签: java json jackson

我一直在尝试使用Jackson注释来避免循环关联,但它似乎没有按预期工作,我仍然得到一个stackoverflow

Allergens上课:

import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the allergens database table.
 * 
 */
@Entity
@Table(name="allergens")
@NamedQuery(name="Allergen.findAll", query="SELECT a FROM Allergen a")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")

public class Allergen{
    private static final long serialVersionUID = 1L;

    @Id
    private int id;

    private boolean isEnabled;

    private String title;

    //bi-directional many-to-one association to Recipe
    @ManyToOne
    @JsonManagedReference
    private Recipe recipe;

    //+getters/setters

Recipe班级

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;


/**
 * The persistent class for the recipes database table.
 * 
 */
@Entity
@Table(name="recipes")
@NamedQuery(name="Recipe.findAll", query="SELECT r FROM Recipe r")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Recipe{
    private static final long serialVersionUID = 1L;

    @Id
    private int id;

    private String complexity;

    private int cookingTime;

    private String description;

    private int estimatedTime;

    private String imageUrl;

    private String information;

    private boolean isPromoted;

    private int preparationTime;

    private float servings;

    private String title;

    private String type;

    //bi-directional many-to-one association to Allergen
    @OneToMany(mappedBy="recipe")
    @JsonBackReference
    private List<Allergen> allergens;

//+getters/setters

我也尝试使用@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")注释这两个类,但遗憾的是这也没有用

我有什么遗漏吗?

此外,我的pom.xml包含

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>

杰克逊还需要其他什么吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试在导致循环引用的属性上添加@JsonIgnore。这将告诉杰克逊不要序列化该财产。