请求帮助来解决com.fasterxml.jackson.databind.JsonMappingException:无限递归

时间:2013-08-09 02:53:18

标签: java json jackson

我有一个具有内部非静态类的类,该类引用父

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注释子项对子项的引用父节点。

1 个答案:

答案 0 :(得分:3)

如上面评论所述,发布的代码很容易产生StackOverflowError

  1. Entry#getPercent()
  2. 致电HighChartSeriesPercents#calculatePercents
  3. 致电Entry#getPercent()等等
  4. 所以问题与杰克逊无关。

    如果您更改逻辑以在value中使用calculatePercents(),则可以避免这种情况。