Gson只用一种方式序列化循环引用

时间:2014-03-28 18:56:46

标签: java json serialization gson circular-reference

我有以下结构:

abstract class Node {
    Connector output;

    @Expose
    List<Connector> inputs;

    @Expose
    String someproperty;
    @Expose
    int someother;
    int thirdOne;
    ...
}

abstract class Connector {
    @Expose
    Node owner;
    @Expose
    Connector peer;

    public void connect(Connector peer) {
      this.peer=peer;
      peer.peer=this;
    }
    ...
}

应序列化为JSON:

{
    ConcreteNodeClassName1: {
       someproperty:"foo",
       someother: 1,
       children: {
         {ConcreteNodeClassName2: ...
          children:{
            ...
          }
         }
       }
   }
}

每个节点都有一个输出连接器和几个输入连接器。连接器通过owner字段引用拥有节点。

如果我现在调用gson.toJson(rootNode);,我会收到堆栈溢出异常,因为owner字段指向拥有模块。但是需要暴露所有者字段,以便让gson下降到下一个节点。

我也尝试过编写自定义序列化程序 - 但没有成功。

如何解决这个问题?

0 个答案:

没有答案