【发布时间】:2013-08-09 02:53:17
【问题描述】:
我有一个类,它有一个指向父级的内部非静态类
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["entries"]);嵌套的 例外是 com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError)(通过引用链: my.package.HighChartSeriesPercents["entries"])
我尝试将 Entry 设为 final 并向父级添加引用变量并访问它,还使用 @JsonManagedReference 注释父项列表,@JsonBackReference 注释子级对父项的引用。
【问题讨论】:
-
您是否尝试在带有一个或多个
Entries的HighChartSeriesPercents实例上调用calculatePercents()?你会得到一个 SO 错误,这与 Jackson 无关 -
同意前面的评论;看起来
Entry.getPercent()calculatePercents()- @milkplusvellocet 您应该将其作为答案发布。如果 Jackson 在序列化过程中调用Entry.getPercent()来获取字段值,看起来您的代码很容易导致 SO。 -
啊该死的,谢谢大家,
calculatePercents()应该是e.value而不是e.getPercent()。谢谢。牛奶,您能否发布一个答案,我会接受,请随时将其发布为代码错误和更正。