我有一个具有内部非静态类的类,该类引用父
public static class HighChartSeriesPercents {
private final List<Entry> entries;
private int total;
@JsonIgnore
private transient boolean percentsGenerated;
@JsonIgnore
private final int sortMode;
public HighChartSeriesPercents() {
this(0);
}
public HighChartSeriesPercents(int sortMode) {
this.entries = new ArrayList<>();
this.sortMode = sortMode;
}
public List<Entry> getEntries() {
return Collections.unmodifiableList(entries);
}
public void add(String name, int value) {
total += value;
percentsGenerated = false;
entries.add(new Entry(name, value));
}
@JsonProperty("size")
public int size() {
return entries.size();
}
public void sort() {
Collections.sort(entries);
}
private void calculatePercents() {
for (Entry e : entries) {
e.setPercent((double) e.getPercent() / (double) total);
}
percentsGenerated = true;
}
public class Entry implements Comparable<Entry> {
private final String name;
private final int value;
private double percent;
public Entry(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public double getPercent() {
if (!percentsGenerated) {
calculatePercents();
}
return percent;
}
private void setPercent(double percent) {
this.percent = percent;
}
@Override
public int compareTo(Entry o) {
int r;
if (sortMode == 0) {
r = ObjectUtils.compare(name, o.name);
if (r != 0) {
return r;
}
return ObjectUtils.compare(value, o.value);
} else {
r = ObjectUtils.compare(value, o.value);
if (r != 0) {
return r;
}
return ObjectUtils.compare(name, o.name);
}
}
}
}
每当杰克逊将其序列化时,我得到:
无法编写JSON:无限递归(StackOverflowError)(通过 参考链: my.package.HighChartSeriesPercents [ “条目”]);嵌套 异常是com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError)(通过引用链: my.package.HighChartSeriesPercents [ “条目”])
我尝试将Entry
设为最终并向父母添加引用变量并访问它,同时使用@JsonManagedReference
注释父项条目列表,并@JsonBackReference
注释子项对子项的引用父节点。
答案 0 :(得分:3)
如上面评论所述,发布的代码很容易产生StackOverflowError
。
Entry#getPercent()
HighChartSeriesPercents#calculatePercents
Entry#getPercent()
等等所以问题与杰克逊无关。
如果您更改逻辑以在value
中使用calculatePercents()
,则可以避免这种情况。