0

我有一个类,它有一个内部非静态类,它引用父级

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: Infinite recursion (StackOverflowError) (通过引用链: my.package.HighChartSeriesPercents["entries"])

我尝试制作Entryfinal 并向父级添加一个引用变量并访问它,还为父@JsonManagedReference项列表和@JsonBackReference子项对父项的引用进行注释。

4

1 回答 1

3

正如上面评论中提到的,发布的代码很容易导致StackOverflowError.

  1. Entry#getPercent()
  2. 来电HighChartSeriesPercents#calculatePercents
  3. 电话Entry#getPercent()

所以这个问题与杰克逊无关。

如果您更改要在其中使用的逻辑,value则将calculatePercents()避免。

于 2013-08-09T16:02:41.300 回答