java - Android 中的 Java 树结构错误

标签 java android tree gson

我有一个代表一棵树的类...

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);

问题是 Gson 无法生成预期的文本。无法弄清楚为什么。知道为什么吗?

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)

最佳答案

我想将此问题标记为以下问题的重复项,但似乎我无法这样做,因为该问题没有公认的答案。但基本上,解决方案就在那里。

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.

关于java - Android 中的 Java 树结构错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44089406/

相关文章:

java - 通过在 android 中使用其 Jar 文件来使用 SherlockActionBar 库

从 argv、树 trie 复制时核心被转储

javascript - 如何收集按深度级别分组的树结构的所有节点?

java - Spring Integration 消息轮询

java - 在 Web 应用程序中使用 RxJava Observables 无法解释的缺乏性能改进

Java 项目强制依赖者采用 Java 版本?

c++ - 访问声明已弃用,取而代之的是使用声明;建议 : add the ‘using’ keyword

java - 如何将java属性文件放入apk中?

android - 是否可以使用嵌套的 ScrollView?

现有项目的 Android xml 图形布局/设计未正确加载