Thursday, November 26, 2015

Gson StackOverFlowError

This usually happens when the class you are converting to json refers to itself ..... most commonly when you are using jpa entities with one to many relations ... where parent refers to many children and child refers again to its parent so that you are able to cascade updates.

Solutions :
1- make the variable in the child transient ... but won't work in case of JPA , because you need the entity attributes not transient
2- make another DTO for JSON transfer that doesn't contain this cyclic dependency and map from/to it ...... but too much effort and error prone
3- the clean way : exclude the variable from parsing by gson , how ? mark all attributes that you want it to be parsed with @Expose annotation .... and then on creation of json object use : 


GsonBuilder.excludeFieldsWithoutExposeAnnotation().create()

Now the non exposed attribute won't be converted in json

No comments:

Post a Comment