直接自引用导致循环

Direct self-reference leading to cycle

我正在尝试发送请求以取回对象数组 - Coupon 当我提交请求时我得到了答案 -

Direct self-reference leading to cycle (through reference chain: java.util.HashSet[0] => model.Coupon["emptyCoupon"] => model.Coupon["emptyCoupon"])

model.Coupon 可能是问题所在。 如果请求的优惠券不存在,将返回空优惠券。

public static final int NO_ID = -1;

private static final Coupon EMPTY_COUPON = new Coupon(NO_ID, null, null, null, NO_ID, NO_ID, null, NO_ID, null);

private long id = NO_ID;
private String title;
private LocalDate startDate;
private LocalDate endDate;
private int amount;
private int category;
private String message;
private double price;
private String image;

public Coupon() {
}

private Coupon(long id, String title, LocalDate start_date, LocalDate end_date, int amount, int category,
        String message, double price, String image) {
    this.id = id;
    this.title = title;
    this.startDate = start_date;
    this.endDate = end_date;
    this.amount = amount;
    this.category = category;
    this.message = message;
    this.price = price;
    this.image = image;
}

public Coupon getEmptyCoupon() {
    return EMPTY_COUPON;
}

在添加 EMPTY_COUPON 之前,我对请求没有任何问题。 我想要代码中的 emptyCoupon,我很乐意提供帮助

由于您使用 Jersey 序列化为 JSON 或 XML,您的对象图中可能没有循环。

泽西岛没有像杰克逊那样的 @JsonBackReference,因此您可以考虑将 EMPTY_COUPON 移到单独的 class(类似于 Constants.java)和从那里获取。

其他选项是将 @XmlIgnore 添加到您的字段或切换到另一个 JSON 序列化程序,如 Jackson。