java - gson.toJson() throws StackOverflowError in Servlet -


i have list of objects clients

list<client> clientslist=new arraylist<client>(); clientslist=clientdao.getallclients(); 

entity client has others list attributes:

@manytoone(optional=false) private user createdby;   @manytomany(mappedby = "clients") private set<clienttype> types=new hashset();   @manytoone(optional=false) private leadsource id_leadsource; @manytoone(optional=false) private agencie id_agencie;  @onetomany(cascade=cascadetype.all,mappedby="owner") private set<propertie> properties=new hashset();  @onetomany(cascade=cascadetype.all,mappedby="buyer") private set<sale> sales=new hashset();  @onetomany(cascade=cascadetype.all,mappedby = "client") private set<rent> rents=new hashset();  @onetomany(cascade=cascadetype.all,mappedby = "clientdoc") private set<document> docuements=new hashset(); 

and when try convert list of clients json format

out.write(new gson().tojson(clientslist)); 

i error :

java.lang.stackoverflowerror @ com.google.gson.stream.jsonwriter.beforename(jsonwriter.java:603) @ com.google.gson.stream.jsonwriter.writedeferredname(jsonwriter.java:401) @ com.google.gson.stream.jsonwriter.value(jsonwriter.java:512) @ com.google.gson.internal.bind.typeadapters$8.write(typeadapters.java:270) @ com.google.gson.internal.bind.typeadapters$8.write(typeadapters.java:255) @ com.google.gson.internal.bind.typeadapterruntimetypewrapper.write(typeadapterruntimetypewrapper.java:68) @ com.google.gson.internal.bind.reflectivetypeadapterfactory$1.write(reflectivetypeadapterfactory.java:113) @ com.google.gson.internal.bind.reflectivetypeadapterfactory$adapter.write(reflectivetypeadapterfactory.java:240) 

that because entities have bidirectional connections. example client has set of rents , each rent has reference client. when try serializing client serialize rents , have serialize each client in rent , on. causes stackoverflowerror.

to solve problem have mark properties transient (or use similar anotation), example use transient client in rent marshalling lib ignore property.

in case of gson can other way around marking field do want included in json @expose , creating gson object with:

gson gson = new gsonbuilder().excludefieldswithoutexposeannotation().create(); 

p.s. also, mention converting jpa entity json , sending somewhere not idea. i'd recommend creating dto(data transfer object) class include info need , ideally using simple types int, date, string , on. if have questions approach can google dto, data transfer object or follow link: https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm


Comments

Popular posts from this blog

cookies - Yii2 Advanced - Share session between frontend and mainsite (duplicate of frontend for www) -

angular - password and confirm password field validation angular2 reactive forms -

php - Permission denied. Laravel linux server -