使用Jackson进行有向图的(De)序列化

时间:2014-07-25 12:46:49

标签: java json serialization jackson finite-automata

我有这三个类来表示有向图(有限状态机):

public class Graph {
    public Set<Node> nodes;

    public Graph(@JsonProperty("nodes") Set<Node> nodes) {
        this.nodes = nodes;
    }
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
                  property = "name")
public class Node {
    public String name;
    public Set<Edge> edges;

    public Node(final String name, final Set<Edge> edges) {
        this.edges = edges;
        this.name = name;
    }

    public Node(@JsonProperty("name") String name) {
        this(name, new HashSet<Edge>());
    }
}

public class Edge {
    public String name;
    public Node successor;

    public Edge(@JsonProperty("name") String name,
                @JsonProperty("successor") Node successor) {
        this.name = name;
        this.successor = successor;
    }

我想借助Jackson 2.3.3将它们映射到JSON对象 简单图表的序列化完美无缺,没有无限的向后引用:

{
  "nodes" : [ {
    "name" : "Z1",
    "edges" : [ {
      "name" : "0",
      "successor" : {
        "name" : "Z0",
        "edges" : [ {
          "name" : "0",
          "successor" : "Z0"
        }, {
          "name" : "1",
          "successor" : "Z1"
        } ]
      }
    }, {
      "name" : "1",
      "successor" : "Z1"
    } ]
  }, "Z0" ]
}

但是当我想反序列化这个确切的JSON时,杰克逊给了我一个错误:

com.fasterxml.jackson.databind.JsonMappingException: Could not resolve Object Id
    [Z0] (for [simple type, class graph.Node]) -- 
    unresolved forward-reference? (through reference chain: 
    graph.Node["edges"]->graph.Node["edges"])

我可以看出,那个节点Z0不能被引用,因为它仍然在构造中#34;所以我怎么告诉Jackson它必须首先构造节点然后再添加边缘的参考文献?

0 个答案:

没有答案