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

Don't increase compiler error level .... Or at least think well before doing that

You might think ..... Oh yeah, I don't want a tiny small error in my application, neither a small warning and worse -not the concept but your reaction- I want to stick to coding standards ,  so I will raise the compiler error level to consider every inconvenience as a nice red error ...... And yes don't worry I am already using maven so I don't really depend on these errors in my productivity.

Don't do it .... I advice

By time, and when your team member size increases and the application gets older and older with many people might successively commit changes to the same portion of code and every one putting his nice touch, you will get used to the 21342235123523 errors appearing in your error console and simply you will never look at it .... and the red color in your code will be as normal as the blue color of the sky.

And this has two -or may be more- draw backs :

1- You won't like looking to your code
 And more importantly :
2- The real problems and errors will hide in the pile of fake errors and are not always easy to figure out using other compilers.... build path errors of dependencies are one of the examples.