直接自引用导致循环超类问题JSON

时间:2021-10-14 11:23:33

I have tried several things I found while searching but nothing helped or I did not implement it correctly.

我在搜索过程中尝试了几件我发现的东西,但没有任何帮助,或者我没有正确实现它。

Error I'm getting

我得到的错误

Direct self-reference leading to cycle (through reference chain: io.test.entity.bone.Special["appInstance"]->io.test.entity.platform.ApplicationInstance["appInstance"])

Both these extend the base entity and in the base (super class) it has an appInstance as well.

这两个都扩展了基本实体,而在基类(超类)中它也有一个appInstance。

Base entity looks similar to this

基本实体看起来与此类似

@MappedSuperclass
public abstract class BaseEntity implements Comparable, Serializable {

@ManyToOne
protected ApplicationInstance appInstance;

//getter & setter

}

Application entity looks like this

应用程序实体如下所示

public class ApplicationInstance extends BaseEntity implements Serializable { 
   private List<User> users;
// some other properties (would all have the same base and application instance . User entity will look similar to the Special.)
}

Special entity

特殊实体

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
@JsonIgnoreProperties({"createdBy", "appInstance", "lastUpdatedBy"})
public class Special extends BaseEntity implements Serializable {

    @NotNull
    @Column(nullable = false)
    private String name;

    @Column(length = Short.MAX_VALUE)
    private String description;

    @NotNull
    @Column(nullable = false)
    private Double price;

    @OneToOne
    private Attachment image;

    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = SpecialTag.class)
    @CollectionTable(name = "special_tags")
    @Column(name = "specialtag")
    private List<SpecialTag> specialTags;

    @Temporal(TemporalType.TIME)
    private Date specialStartTime;

    @Temporal(TemporalType.TIME)
    private Date specialEndTime;

    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = WeekDay.class)
    @CollectionTable(name = "available_week_days")
    @Column(name = "weekday")
    private List<WeekDay> availableWeekDays;

    @OneToMany(mappedBy = "special", cascade = CascadeType.REFRESH)
    private List<SpecialStatus> statuses;

    @OneToMany(mappedBy = "special", cascade = CascadeType.REFRESH)
    private List<SpecialReview> specialReviews;

    @Transient
    private Integer viewed;

    private Boolean launched;

    @OneToMany(mappedBy = "special")
    private List<CampaignSpecial> specialCampaigns;


  @Override
  @JsonIgnore
  public ApplicationInstance getAppInstance() {
    return super.getAppInstance(); 
  }
}

All entities in Special inherits from BaseEntity which contains AppInstance

Special中的所有实体都继承自BaseEntity,其中包含AppInstance

then i have a method to get the special

然后我有一个方法来获得特殊

@GET
@Path("{ref}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(value = MediaType.TEXT_PLAIN)
public Special findByGuestRef(@PathParam("ref") String pRefeference) {
  // find the special and return it
 return special;
}

On the special entity I tried the following

在特殊实体上我尝试了以下内容

  • Added jsonIgnoreProperties
  • 添加了jsonIgnoreProperties
  • Added an override for appInstance to annotate with @JsonIgnore
  • 添加了appInstance的覆盖以使用@JsonIgnore进行批注
  • @JsonIdentityInfo
  • @JsonIdentityInfo

links for the above

上面的链接

none of those solutions works. Am I doing something wrong?

这些解决方案都不起作用。难道我做错了什么?

Note: Would it also just be possible to edit special, since the other entities are in a different package and would not like to edit them.

注意:是否也可以编辑特殊,因为其他实体位于不同的包中,并且不想编辑它们。

2 个解决方案

#1


2  

Usually excluding attributes in a response is as easy as adding a @JsonIgnore annotation to their getters, but if you don't want to add this annotation to a parent class, you could override the getter and then add the annotation on it:

通常排除响应中的属性就像在其getter中添加@JsonIgnore注释一样简单,但如果您不想将此注释添加到父类,则可以覆盖getter,然后在其上添加注释:

public class Special extends BaseEntity implements Serializable {
    ...
    @JsonIgnore
    public ApplicationInstance getAppInstance() {
        return this.appInstance;
    }
    ...
}

NOTE: As there are several frameworks, make sure that you are using the correct @JsonIgnore annotation or it will be ignored, see this answer for instance.

注意:由于有几个框架,请确保使用正确的@JsonIgnore注释,否则它将被忽略,例如,请参阅此答案。

Another option, more "manual", is just creating a bean for the response which would be a subset of the Special instance:

另一个选项,更“手动”,只是为响应创建一个bean,它将是Special实例的一个子集:

@GET
@Path("{ref}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(value = MediaType.TEXT_PLAIN)
public SpecialDTO findByGuestRef(@PathParam("ref") String pRefeference) {
  // find the special and return it
 return new SpecialDTO(special);
}


public class SpecialDTO {

    //declare here only the attributes that you want in your response

    public SpecialDTO(Special sp) {
        this.attr=sp.attr; // populate the needed attributes
    }

}

#2


0  

To me, problem seems to be in the Special object and the fields being initialized in it. I guess that there is a circular reference detected when serialisation happens. Something similar to:

对我来说,问题似乎出现在Special对象和正在其中初始化的字段中。我猜在序列化发生时检测到循环引用。类似于:

class A {
    public A child;
    public A parent;
}

A object = new A();
A root = new A();
root.child = object;
object.parent = root;

In the above code, whenever you will try to seralize either of these objects, you will face the same problem. Note that public fields are not recommended.

在上面的代码中,每当您尝试seralize这些对象中的任何一个时,您将面临同样的问题。请注意,不建议使用公共字段。

I'll suggest to peek into your Special object and the references set in it.

我建议您查看您的Special对象及其中的参考设置。

#1


2  

Usually excluding attributes in a response is as easy as adding a @JsonIgnore annotation to their getters, but if you don't want to add this annotation to a parent class, you could override the getter and then add the annotation on it:

通常排除响应中的属性就像在其getter中添加@JsonIgnore注释一样简单,但如果您不想将此注释添加到父类,则可以覆盖getter,然后在其上添加注释:

public class Special extends BaseEntity implements Serializable {
    ...
    @JsonIgnore
    public ApplicationInstance getAppInstance() {
        return this.appInstance;
    }
    ...
}

NOTE: As there are several frameworks, make sure that you are using the correct @JsonIgnore annotation or it will be ignored, see this answer for instance.

注意:由于有几个框架,请确保使用正确的@JsonIgnore注释,否则它将被忽略,例如,请参阅此答案。

Another option, more "manual", is just creating a bean for the response which would be a subset of the Special instance:

另一个选项,更“手动”,只是为响应创建一个bean,它将是Special实例的一个子集:

@GET
@Path("{ref}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(value = MediaType.TEXT_PLAIN)
public SpecialDTO findByGuestRef(@PathParam("ref") String pRefeference) {
  // find the special and return it
 return new SpecialDTO(special);
}


public class SpecialDTO {

    //declare here only the attributes that you want in your response

    public SpecialDTO(Special sp) {
        this.attr=sp.attr; // populate the needed attributes
    }

}

#2


0  

To me, problem seems to be in the Special object and the fields being initialized in it. I guess that there is a circular reference detected when serialisation happens. Something similar to:

对我来说,问题似乎出现在Special对象和正在其中初始化的字段中。我猜在序列化发生时检测到循环引用。类似于:

class A {
    public A child;
    public A parent;
}

A object = new A();
A root = new A();
root.child = object;
object.parent = root;

In the above code, whenever you will try to seralize either of these objects, you will face the same problem. Note that public fields are not recommended.

在上面的代码中,每当您尝试seralize这些对象中的任何一个时,您将面临同样的问题。请注意,不建议使用公共字段。

I'll suggest to peek into your Special object and the references set in it.

我建议您查看您的Special对象及其中的参考设置。