Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid gson tojson recursion

Tags:

java

json

gson

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?

like image 220
Anton Avatar asked Feb 21 '26 14:02

Anton


2 Answers

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.

like image 200
Mo1989 Avatar answered Feb 23 '26 05:02

Mo1989


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
like image 40
boehm_s Avatar answered Feb 23 '26 07:02

boehm_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!