Gson使用递归依赖关系反序列化复杂对象

时间:2013-10-06 02:27:46

标签: java json deserialization gson recursive-datastructures

我有几个包含彼此递归依赖的类,我使用Gson GraphAdapterBuilder将它们序列化为JSON格式,它运行得很好。现在我想将它们反序列化为相同的结构,但无法找到方法。

我做了一个例子:

class ClassA{
    public int field;
    public ClassB parent;
    public ClassA(int f, ClassB p){
        field = f;
        parent = p;
    }
}

class ClassB{
    public Vector<ClassA> vector = new Vector<ClassA>();
}

...

ClassB b = new ClassB();        

ClassA a1 = new ClassA(1,b);
ClassA a2 = new ClassA(2,b);
ClassA a3 = new ClassA(3,b);

b.vector.add(a1);
b.vector.add(a2);
b.vector.add(a3);

//Serializing object b

GsonBuilder gsonBuilder = new GsonBuilder();

new GraphAdapterBuilder()
    .addType(ClassA.class)
    .addType(ClassB.class)
    .registerOn(gsonBuilder);

Gson gson = gsonBuilder.create();

String json = gson.toJson(b);

输出给了我想要的东西:

{"0x1":{"vector":["0x2","0x3","0x4"]},"0x2":{"field":1,"parent":"0x1"},"0x3":{"field":2,"parent":"0x1"},"0x4":{"field":3,"parent":"0x1"}}

有没有办法将json字符串反序列化为ClassB的对象?

2 个答案:

答案 0 :(得分:8)

好的,我找到了解决方案。这很简单。只需使用函数 fromJson 而不是 toJson 使用相同的GraphAdapterBuilder结构。

    ...
    GsonBuilder gsonBuilder = new GsonBuilder();
    new GraphAdapterBuilder()
            .addType(ClassA.class)
            .addType(ClassB.class)
            .registerOn(gsonBuilder);
    gson = gsonBuilder.create();
    СlassB B = gson.fromJson(json,ClassB.class);

    System.out.println("B " + B.vector);
    for(ClassA classA:B.vector){
        System.out.println(classA.field + "  " + classA.parent);
    }

输出是:

    B [ClassA@10178f2b, ClassA@7ab8584d, ClassA@5cad662c]
    1  ClassB@7c0f023c
    2  ClassB@7c0f023c
    3  ClassB@7c0f023c

答案 1 :(得分:-4)

class ClassA{
    public int field;
    public String parent;
    public ClassA(int f, String parent){
        this.field = f;
        this.parent = parent;
    }
}

class ClassB{
    public List<String> vector;
}

String str1 = "{\"0x1\":{\"vector\":[\"0x2\",\"0x3\",\"0x4\"]},\"0x2\":{\"field\":1,\"parent\":\"0x1\"},\"0x3\":{\"field\":2,\"parent\":\"0x1\"},\"0x4\":{\"field\":3,\"parent\":\"0x1\"}}";

JsonParser parser = new JsonParser();
JsonObject element = (JsonObject)parser.parse(str1);
JsonElement responseWrapper = element.get("0x1");
Gson gson = new Gson();
ClassB  classB =gson.fromJson(responseWrapper,ClassB.class);
System.out.println(classB.vector);
for (String key:classB.vector) {
      responseWrapper = element.get( key);
      ClassA  classA =gson.fromJson(responseWrapper,ClassA.class);
      System.out.println(classA.field);
      System.out.println(classA.parent);

}