gpt4 book ai didi

java - Android 中的 Java 树结构错误

转载 作者:行者123 更新时间:2023-12-02 13:07:24 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com