我的游戏中有我希望能够序列化为 JSON 的对象。问题是在它们具有指向“所有者”对象的指针时尝试序列化它们会导致堆栈溢出。
例如:
public class Entity
{
Vector2 loc;
Item item;
public Entity(Vector2 loc)
{
this.loc = loc;
this.item = new Item(this.loc, this);
}
}
public class Item
{
Vector2 loc;
Entity owner;
public Item(Vector2 loc, Entity owner)
{
this.loc = loc;
this.owner = owner;
}
}
如果我再打电话
Json json = new Json();
System.out.println(json.prettyprint(instanceOfEntity));
我遇到堆栈溢出。
我意识到这可能是一个架构问题,但我不确定解决它的最佳方法。这个问题的解决方案是什么?
最佳答案
将 Owner
字段设置为 transient
应该可以解决问题,并避免在序列化时出现循环引用:
public class Item
{
Vector2 loc;
transient Entity owner;
public Item(Vector2 loc, Entity owner)
{
this.loc = loc;
this.owner = owner;
}
}
How does marking a field as transient make it possible to serialise an object
关于java - 序列化具有双向引用的对象时如何避免堆栈溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20550141/