0

I have this Class that represents a tree...

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Leitur<T> implements Iterable<Leitur<T>> {

    T data;
    Leitur<T> parent;
    List<Leitur<T>> children;

    public Leitur(T data) {
        this.data = data;
        this.children = new LinkedList<Leitur<T>>();
    }

    public Leitur<T> addChild(T child) {
        Leitur<T> childNode = new Leitur<T>(child);
        childNode.parent = this;
        this.children.add(childNode);
        return childNode;
    }

    @Override
    public Iterator<Leitur<T>> iterator() {
        return null;
    }
}

...

Leitur<String> root = new Leitur<String>("aaa");
Leitur<String> node0 = root.addChild("node0");
Leitur<String> node00 = node0.addChild("node00");
Leitur<String> node000 = node00.addChild(null);
Leitur<String> node1 = root.addChild("node1");
Leitur<String> node10 = node1.addChild("node10");
Leitur<String> node100 = node10.addChild(null);
String text = new Gson().toJson(root);

The problem is that Gson can't produce the expected text. Can't figurate whay. Any idea whay?

AndroidRuntime: FATAL EXCEPTION: main Process: pt.sys.opencvdemo, PID: 13475 java.lang.StackOverflowError: stack size 8MB at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:401) at com.google.gson.stream.JsonWriter.beginArray(JsonWriter.java:287) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:95) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61) at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:976) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)

DCD
  • 325
  • 6
  • 25

1 Answers1

1

I wanted to flag this question as a duplicate of the below question, but seems I can't do that because that one does not have an accepted answer. But basically, the solution is there.

Getting stackoverflowerror from Gson while converting hashmap to JSON object

So how can we fix this? It depends on what behavior you want. One easy option is to prevent Gson from attempting to serialize the parent field (we don't need it, as we can reconstruct it from the children list). To do this just mark parent as transient and Gson will not include it in the result.

Community
  • 1
  • 1
tima
  • 1,498
  • 4
  • 20
  • 28