JSON Jackson注解忽略

4
我正在使用@JsonIgnore注解,但仍然出现堆栈溢出错误。
存在循环引用,注解被忽略。
@Entity
@NamedQuery(name="Buch.findAll", query="SELECT b FROM Buch v")
public class Buch implements Serializable {
    private static final long serialVersionUID = 1L;

    ...

    //bi-directional many-to-one association to Titel
    @OneToOne(mappedBy="buch")
    @JsonIgnore
    private Titel Titel;

    ...

    @JsonIgnore
    public Titel getTitel() {
        return this.verein;
    }

    @JsonIgnore
    public void setTitel(Titel titel) {
        this.titel= titel;
    }
}

考虑发布实际代码和实际堆栈跟踪。如果代码很多,可以考虑从您正在工作的项目中提取等效但更短/压缩的代码示例来演示问题。(即自包含代码示例。)最后,作为程序设计的一部分,您可能还希望将模型逻辑(带有@Entity注释)与输入/输出序列化格式(带有Jackson注释)解耦成单独的类,并在需要时在两种类型之间进行转换。这样您就可以简化。 - user268396
顺便提一下,关系是一对一而不是你在评论中说的多对一 :) - niceman
2个回答

2

你的代码存在几个问题:

  • 你在字段和它的访问器(getter和setter)上都使用了@JsonIgnore注释,这样做是不必要的,只映射其中一个即可。我建议你只映射getter方法,并使用@JsonIgnore
  • 另一件事是你的Titelgetter方法没有正确实现,它应该返回Titel字段,但你却返回this.verein,这是完全错误的,会破坏你代码的逻辑,你需要进行更正。

我的建议是只在你需要更正的getter方法上使用@JsonIgnore

@JsonIgnore
public Titel getTitel() {
    return this.Titel;
}

1

我认为这段代码不起作用,因为你在一个setter上使用了@JsonIgnore,导致(jackson ex)无法设置标题。请将其改为@JsonSetter,并在getter上添加@JsonIgnore:

@JsonIgnore
public Titel getTitel() {
    return this.verein;
}

@JsonSetter
public void setTitel(Titel titel) {
    this.titel= titel;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接