Gson deserialize complex object with recursive dependencies

早过忘川 提交于 2019-12-04 19:23:10

问题


I have several classes that contain a recursive dependency on each other and I serialize them to JSON format with Gson GraphAdapterBuilder, and it works perfectly. Now I want to deserialize them into the same structure but can't find out how.

I've made an example:

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);

Output is giving me what I want:

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

Is there a way to deserialize that json string back into object of ClassB?


回答1:


Okay, I found solution. It was very simple. Just had to use the function fromJson instead of toJson with the same GraphAdapterBuilder structure.

    ...
    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);
    }

Output is:

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



回答2:


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);

}


来源:https://stackoverflow.com/questions/19204796/gson-deserialize-complex-object-with-recursive-dependencies

工具导航Map