Anton
Anton

Reputation: 559

how to avoid gson tojson recursion

I have very simple class:

MyObject:
 - String index;
 - MyObject parent;
 - List<MyObject> childs;

I want to print stored information into json. I use toJson function of Gson library. But due to every child has a link to parent object I face with infinite loop recursion. Is there a way to define that gson shall print only parent index for every child instead of dumping full information?

Upvotes: 3

Views: 3959

Answers (2)

boehm_s
boehm_s

Reputation: 5544

I ran into the same problem today and found another solution that I'd like to share :

You can declare an attribute as transient and it won't be serialized or deserialized :

public class MyObject{
  String index;
  transient MyObject parent;
  List<MyObject> children;
}

Gson gson = new Gson();
gson.toJson(obj); // parent will not show up

Upvotes: 2

Mo1989
Mo1989

Reputation: 2494

you need to use the @Expose annotation.

public class MyObject{

    @Expose
    String index;

    MyObject parent;

    @Expose
    List<MyObject> children;

}

Then generate the json using

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
jsonString = gson.toJson(data);

Edit: you can do a dfs parse when you convert it back to the object. Just make a method like:

public void setParents(MyObj patent){ 
    this.parent=parent; 
    for(MyObj o:children){
        o.setParent(this); 
    }
}

and call it for the root object.

Upvotes: 6

Related Questions