gson.toJson() throws StackOverflowErrorGson: How to exclude specific fields from Serialization without annotationsHow Android SharedPreferences save/store objectstore and retrieve a class object in shared preferenceGson StackOverflowErrorgson.toJson() throws StackOverflowError in ServletStackOverflowError when using JsonSerializer with Gson and ScalaHow to get around circular references when using Gson?Gson.fromJson() throws StackOverflowErrorCan't transfer List to JsonGetting stackoverflowerror from Gson while converting hashmap to JSON objectWhat is a StackOverflowError?Try-finally block prevents StackOverflowErrorCould not serialize object cause of HibernateProxyError in serializaion of Hibernate DTO using GSONAndroid - gson.toJson throws StackOverFlowError on ArrayList<OverlayItem>Why doesn't this statement throw a StackOverflowError?gson.toJson() throws StackOverflowError in ServletTrying to serialize an object to json using GSON -> get huge recursive errorAmadeus API - java.lang ExceptionGSON.toJson(new RuntimeException()) throws StackOverflowError

Defining the standard model of PA so that a space alien could understand

Looking for a soft substance that doesn't dissolve underwater

How to respond to an upset student?

Why colon to denote that a value belongs to a type?

Does the unit of measure matter when you are solving for the diameter of a circumference?

Make 24 using exactly three 3s

Which is the common name of Mind Flayers?

Who will lead the country until there is a new Tory leader?

How to illustrate the Mean Value theorem?

If a person had control of every single cell of their body, would they be able to transform into another creature?

At what point in European history could a government build a printing press given a basic description?

Construct a word ladder

Does Nitrogen inside commercial airliner wheels prevent blowouts on touchdown?

Can I install both XCode & Android Studio on MacBook Air with only 8 GB of Ram

What does this symbol on the box of power supply mean?

Plot twist where the antagonist wins

What are these arcade games in Ghostbusters 1984?

Where is the logic in castrating fighters?

Should I disclose a colleague's illness (that I should not know) when others badmouth him

Should one buy new hardware after a system compromise?

Should breaking down something like a door be adjudicated as an attempt to beat its AC and HP, or as an ability check against a set DC?

I think I may have violated academic integrity last year - what should I do?

Why do most published works in medical imaging try to reduce false positives?

When and what was the first 3D acceleration device ever released?



gson.toJson() throws StackOverflowError


Gson: How to exclude specific fields from Serialization without annotationsHow Android SharedPreferences save/store objectstore and retrieve a class object in shared preferenceGson StackOverflowErrorgson.toJson() throws StackOverflowError in ServletStackOverflowError when using JsonSerializer with Gson and ScalaHow to get around circular references when using Gson?Gson.fromJson() throws StackOverflowErrorCan't transfer List to JsonGetting stackoverflowerror from Gson while converting hashmap to JSON objectWhat is a StackOverflowError?Try-finally block prevents StackOverflowErrorCould not serialize object cause of HibernateProxyError in serializaion of Hibernate DTO using GSONAndroid - gson.toJson throws StackOverFlowError on ArrayList<OverlayItem>Why doesn't this statement throw a StackOverflowError?gson.toJson() throws StackOverflowError in ServletTrying to serialize an object to json using GSON -> get huge recursive errorAmadeus API - java.lang ExceptionGSON.toJson(new RuntimeException()) throws StackOverflowError






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








67















I would like to generate a JSON String from my object:



Gson gson = new Gson();
String json = gson.toJson(item);


Everytime I try to do this, I get this error:



14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)


These are the attributes of my BomItem class:



private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;


Attributes of my referenced BomModule class:



private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;


Any idea what causes this error? How can I fix it?










share|improve this question
























  • Could happen if you put an object instance inside itself somewhere inside the gson.

    – Christophe Roussy
    Nov 24 '15 at 10:12











  • The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

    – Siddharth
    Jun 3 '17 at 11:40

















67















I would like to generate a JSON String from my object:



Gson gson = new Gson();
String json = gson.toJson(item);


Everytime I try to do this, I get this error:



14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)


These are the attributes of my BomItem class:



private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;


Attributes of my referenced BomModule class:



private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;


Any idea what causes this error? How can I fix it?










share|improve this question
























  • Could happen if you put an object instance inside itself somewhere inside the gson.

    – Christophe Roussy
    Nov 24 '15 at 10:12











  • The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

    – Siddharth
    Jun 3 '17 at 11:40













67












67








67


8






I would like to generate a JSON String from my object:



Gson gson = new Gson();
String json = gson.toJson(item);


Everytime I try to do this, I get this error:



14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)


These are the attributes of my BomItem class:



private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;


Attributes of my referenced BomModule class:



private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;


Any idea what causes this error? How can I fix it?










share|improve this question
















I would like to generate a JSON String from my object:



Gson gson = new Gson();
String json = gson.toJson(item);


Everytime I try to do this, I get this error:



14:46:40,236 ERROR [[BomItemToJSON]] Servlet.service() for servlet BomItemToJSON threw exception
java.lang.StackOverflowError
at com.google.gson.stream.JsonWriter.string(JsonWriter.java:473)
at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:347)
at com.google.gson.stream.JsonWriter.value(JsonWriter.java:440)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:235)
at com.google.gson.internal.bind.TypeAdapters$7.write(TypeAdapters.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:843)


These are the attributes of my BomItem class:



private int itemId;
private Collection<BomModule> modules;
private boolean deprecated;
private String partNumber;
private String description; //LOB
private int quantity;
private String unitPriceDollar;
private String unitPriceEuro;
private String discount;
private String totalDollar;
private String totalEuro;
private String itemClass;
private String itemType;
private String vendor;
private Calendar listPriceDate;
private String unitWeight;
private String unitAveragePower;
private String unitMaxHeatDissipation;
private String unitRackSpace;


Attributes of my referenced BomModule class:



private int moduleId;
private String moduleName;
private boolean isRootModule;
private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;
private Collection<BomItem> items;
private int quantity;


Any idea what causes this error? How can I fix it?







java json object gson stack-overflow






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 18 '12 at 13:18







nimrod

















asked Apr 18 '12 at 13:03









nimrodnimrod

2,3622168134




2,3622168134












  • Could happen if you put an object instance inside itself somewhere inside the gson.

    – Christophe Roussy
    Nov 24 '15 at 10:12











  • The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

    – Siddharth
    Jun 3 '17 at 11:40

















  • Could happen if you put an object instance inside itself somewhere inside the gson.

    – Christophe Roussy
    Nov 24 '15 at 10:12











  • The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

    – Siddharth
    Jun 3 '17 at 11:40
















Could happen if you put an object instance inside itself somewhere inside the gson.

– Christophe Roussy
Nov 24 '15 at 10:12





Could happen if you put an object instance inside itself somewhere inside the gson.

– Christophe Roussy
Nov 24 '15 at 10:12













The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

– Siddharth
Jun 3 '17 at 11:40





The Exception looses the root cause an starts the log with JsonWriter.java:473), how do identify the root cause of the Gson stackoverflow

– Siddharth
Jun 3 '17 at 11:40












14 Answers
14






active

oldest

votes


















66














That problem is that you have a circular reference.



In the BomModule class you are referencing to:



private Collection<BomModule> parentModules;
private Collection<BomModule> subModules;


That self reference to BomModule, obviously, not liked by GSON at all.



A workaround is just set the modules to null to avoid the recursive looping. This way I can avoid the StackOverFlow-Exception.



item.setModules(null);


Or mark the fields you don't want to show up in the serialized json by using the transient keyword, eg:



private transient Collection<BomModule> parentModules;
private transient Collection<BomModule> subModules;





share|improve this answer

























  • Yes a BomModule object can be part of another BomModule object.

    – nimrod
    Apr 18 '12 at 13:06











  • But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

    – nimrod
    Apr 18 '12 at 13:11











  • @dooonot: Do any of the objects in the collection reference their parent object?

    – SLaks
    Apr 18 '12 at 13:15











  • I am not sure if I got you right, but yes. Please see the updated question above.

    – nimrod
    Apr 18 '12 at 13:17











  • @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

    – SLaks
    Apr 18 '12 at 13:19


















24














I had this problem when I had a Log4J logger as a class property, such as:



private Logger logger = Logger.getLogger(Foo.class);


This can be solved by either making the logger static or simply by moving it into the actual function(s).






share|improve this answer




















  • 4





    Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

    – christopher
    Nov 19 '14 at 20:54






  • 1





    another way to solve it, is by adding transient modifier to the field

    – gawi
    Nov 17 '16 at 16:03











  • logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

    – stolsvik
    Apr 19 '18 at 9:42


















16














If you're using Realm and you get this error, and the object giving the trouble extends RealmObject, don't forget to do realm.copyFromRealm(myObject) to create a copy without all the Realm bindings before passing through to GSON for serialization.



I'd missed doing this for just one amongst a bunch of objects being copied... took me ages to realise as the stack trace doesn't name the object class/type. Thing is, the issue is caused by a circular reference, but it's a circular reference somewhere in the RealmObject base class, not your own subclass, which makes it harder to spot!






share|improve this answer

























  • That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

    – Ricardo Mutti
    May 25 '17 at 20:11











  • Using realm, that was exactly the solution that solves the problem, thanks

    – Jude Fernandes
    Oct 20 '18 at 8:18











  • You saved my time !!! thank you

    – Amjad Tubasi
    Apr 20 at 23:47


















11














As SLaks said StackOverflowError happen if you have circular reference in your object.



To fix it you could use TypeAdapter for your object.



For example, if you need only generate String from your object you could use adapter like this:



class MyTypeAdapter<T> extends TypeAdapter<T> 
public T read(JsonReader reader) throws IOException
return null;


public void write(JsonWriter writer, T obj) throws IOException
if (obj == null)
writer.nullValue();
return;

writer.value(obj.toString());




and register it like this:



Gson gson = new GsonBuilder()
.registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>())
.create();


or like this, if you have interface and want to use adapter for all its subclasses:



Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>())
.create();





share|improve this answer






























    6














    My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.



    With Gson you can mark the fields you do want to be included in json with @Expose like this:



    @Expose
    String myString; // will be serialized as myString


    and create the gson object with:



    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();


    Circular references you just do not expose. That did the trick for me!






    share|improve this answer

























    • Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

      – jDub9
      Aug 6 '18 at 11:49











    • @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

      – ffonz
      Aug 21 '18 at 13:15


















    2














    This error is common when you have a logger in your super class. As @Zar suggested before, you can use static for your logger field, but this also works:



    protected final transient Logger logger = Logger.getLogger(this.getClass());


    P.S. probably it will work and with @Expose annotation check more about this here: https://stackoverflow.com/a/7811253/1766166






    share|improve this answer
































      1














      I have the same problem. In my case the reason was that constructor of my serialized class take context variable, like this:



      public MetaInfo(Context context)


      When I delete this argument, error has gone.



      public MetaInfo()





      share|improve this answer


















      • 1





        I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

        – user802467
        Nov 4 '14 at 23:22











      • @user802467 do you mean android service?

        – Preetam
        May 2 '16 at 7:43


















      1














      Edit: Sorry for my bad, this is my first answer. Thanks for your advises.



      I create my own Json Converter



      The main solution I used is to create a parents object set for each object reference. If a sub-reference points to existed parent object, it will discard.
      Then I combine with an extra solution, limiting the reference time to avoid infinitive loop in bi-directional relationship between entities.



      My description is not too good, hope it helps you guys.



      This is my first contribution to Java community (solution to your problem). You can check it out ;)
      There is a README.md file
      https://github.com/trannamtrung1st/TSON






      share|improve this answer




















      • 2





        A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

        – Paul Roub
        Jul 23 '18 at 4:13






      • 2





        Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

        – Shree
        Jul 23 '18 at 4:14











      • Thanks so much. I had edit my answer. Hope it would be fine :D

        – Trần Nam Trung
        Jul 23 '18 at 4:26











      • Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

        – LAD
        Jul 23 '18 at 4:42


















      0














      In Android, gson stack overflow turned out to be the declaration of a Handler. Moved it to a class that isn't being deserialized.



      Based on Zar's recommendation, I made the the handler static when this happened in another section of code. Making the handler static worked as well.






      share|improve this answer
































        0














        BomItem refers to BOMModule (Collection<BomModule> modules), and BOMModule refers to BOMItem (Collection<BomItem> items). Gson library doesn't like circular references. Remove this circular dependency from your class. I too had faced same issue in the past with gson lib.






        share|improve this answer






























          0














          I had this problem occur for me when I put:



          Logger logger = Logger.getLogger( this.getClass().getName() );


          in my object...which made perfect sense after an hour or so of debugging!






          share|improve this answer






























            0














            For Android users, you cannot serialize a Bundle due to a self-reference to Bundle causing a StackOverflowError.



            To serialize a bundle, register a BundleTypeAdapterFactory.






            share|improve this answer






























              0














              Avoid unnecessary workarounds, like setting values to null or making fields transient. The right way to do this, is to annotate one of the fields with @Expose and then tell Gson to serialize only the fields with the annotation:



              private Collection<BomModule> parentModules;
              @Expose
              private Collection<BomModule> subModules;

              ...
              Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();





              share|improve this answer






























                0














                I had a similar issue where the class had an InputStream variable which I didn't really have to persist. Hence changing it to Transient solved the issue.






                share|improve this answer























                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10209959%2fgson-tojson-throws-stackoverflowerror%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  14 Answers
                  14






                  active

                  oldest

                  votes








                  14 Answers
                  14






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  66














                  That problem is that you have a circular reference.



                  In the BomModule class you are referencing to:



                  private Collection<BomModule> parentModules;
                  private Collection<BomModule> subModules;


                  That self reference to BomModule, obviously, not liked by GSON at all.



                  A workaround is just set the modules to null to avoid the recursive looping. This way I can avoid the StackOverFlow-Exception.



                  item.setModules(null);


                  Or mark the fields you don't want to show up in the serialized json by using the transient keyword, eg:



                  private transient Collection<BomModule> parentModules;
                  private transient Collection<BomModule> subModules;





                  share|improve this answer

























                  • Yes a BomModule object can be part of another BomModule object.

                    – nimrod
                    Apr 18 '12 at 13:06











                  • But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                    – nimrod
                    Apr 18 '12 at 13:11











                  • @dooonot: Do any of the objects in the collection reference their parent object?

                    – SLaks
                    Apr 18 '12 at 13:15











                  • I am not sure if I got you right, but yes. Please see the updated question above.

                    – nimrod
                    Apr 18 '12 at 13:17











                  • @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                    – SLaks
                    Apr 18 '12 at 13:19















                  66














                  That problem is that you have a circular reference.



                  In the BomModule class you are referencing to:



                  private Collection<BomModule> parentModules;
                  private Collection<BomModule> subModules;


                  That self reference to BomModule, obviously, not liked by GSON at all.



                  A workaround is just set the modules to null to avoid the recursive looping. This way I can avoid the StackOverFlow-Exception.



                  item.setModules(null);


                  Or mark the fields you don't want to show up in the serialized json by using the transient keyword, eg:



                  private transient Collection<BomModule> parentModules;
                  private transient Collection<BomModule> subModules;





                  share|improve this answer

























                  • Yes a BomModule object can be part of another BomModule object.

                    – nimrod
                    Apr 18 '12 at 13:06











                  • But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                    – nimrod
                    Apr 18 '12 at 13:11











                  • @dooonot: Do any of the objects in the collection reference their parent object?

                    – SLaks
                    Apr 18 '12 at 13:15











                  • I am not sure if I got you right, but yes. Please see the updated question above.

                    – nimrod
                    Apr 18 '12 at 13:17











                  • @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                    – SLaks
                    Apr 18 '12 at 13:19













                  66












                  66








                  66







                  That problem is that you have a circular reference.



                  In the BomModule class you are referencing to:



                  private Collection<BomModule> parentModules;
                  private Collection<BomModule> subModules;


                  That self reference to BomModule, obviously, not liked by GSON at all.



                  A workaround is just set the modules to null to avoid the recursive looping. This way I can avoid the StackOverFlow-Exception.



                  item.setModules(null);


                  Or mark the fields you don't want to show up in the serialized json by using the transient keyword, eg:



                  private transient Collection<BomModule> parentModules;
                  private transient Collection<BomModule> subModules;





                  share|improve this answer















                  That problem is that you have a circular reference.



                  In the BomModule class you are referencing to:



                  private Collection<BomModule> parentModules;
                  private Collection<BomModule> subModules;


                  That self reference to BomModule, obviously, not liked by GSON at all.



                  A workaround is just set the modules to null to avoid the recursive looping. This way I can avoid the StackOverFlow-Exception.



                  item.setModules(null);


                  Or mark the fields you don't want to show up in the serialized json by using the transient keyword, eg:



                  private transient Collection<BomModule> parentModules;
                  private transient Collection<BomModule> subModules;






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 22 '18 at 5:09









                  Ren

                  2,62122143




                  2,62122143










                  answered Apr 18 '12 at 13:05









                  SLaksSLaks

                  700k14116661783




                  700k14116661783












                  • Yes a BomModule object can be part of another BomModule object.

                    – nimrod
                    Apr 18 '12 at 13:06











                  • But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                    – nimrod
                    Apr 18 '12 at 13:11











                  • @dooonot: Do any of the objects in the collection reference their parent object?

                    – SLaks
                    Apr 18 '12 at 13:15











                  • I am not sure if I got you right, but yes. Please see the updated question above.

                    – nimrod
                    Apr 18 '12 at 13:17











                  • @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                    – SLaks
                    Apr 18 '12 at 13:19

















                  • Yes a BomModule object can be part of another BomModule object.

                    – nimrod
                    Apr 18 '12 at 13:06











                  • But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                    – nimrod
                    Apr 18 '12 at 13:11











                  • @dooonot: Do any of the objects in the collection reference their parent object?

                    – SLaks
                    Apr 18 '12 at 13:15











                  • I am not sure if I got you right, but yes. Please see the updated question above.

                    – nimrod
                    Apr 18 '12 at 13:17











                  • @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                    – SLaks
                    Apr 18 '12 at 13:19
















                  Yes a BomModule object can be part of another BomModule object.

                  – nimrod
                  Apr 18 '12 at 13:06





                  Yes a BomModule object can be part of another BomModule object.

                  – nimrod
                  Apr 18 '12 at 13:06













                  But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                  – nimrod
                  Apr 18 '12 at 13:11





                  But is that a problem? 'Collection<BomModule> modules' is only a collection, and I think gson should be able to make a simple array out of it?

                  – nimrod
                  Apr 18 '12 at 13:11













                  @dooonot: Do any of the objects in the collection reference their parent object?

                  – SLaks
                  Apr 18 '12 at 13:15





                  @dooonot: Do any of the objects in the collection reference their parent object?

                  – SLaks
                  Apr 18 '12 at 13:15













                  I am not sure if I got you right, but yes. Please see the updated question above.

                  – nimrod
                  Apr 18 '12 at 13:17





                  I am not sure if I got you right, but yes. Please see the updated question above.

                  – nimrod
                  Apr 18 '12 at 13:17













                  @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                  – SLaks
                  Apr 18 '12 at 13:19





                  @dooonot: As I suspected, it goes into an infinite loop when serializing the parent and child collections. What kind JSON do you expect it to write?

                  – SLaks
                  Apr 18 '12 at 13:19













                  24














                  I had this problem when I had a Log4J logger as a class property, such as:



                  private Logger logger = Logger.getLogger(Foo.class);


                  This can be solved by either making the logger static or simply by moving it into the actual function(s).






                  share|improve this answer




















                  • 4





                    Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                    – christopher
                    Nov 19 '14 at 20:54






                  • 1





                    another way to solve it, is by adding transient modifier to the field

                    – gawi
                    Nov 17 '16 at 16:03











                  • logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                    – stolsvik
                    Apr 19 '18 at 9:42















                  24














                  I had this problem when I had a Log4J logger as a class property, such as:



                  private Logger logger = Logger.getLogger(Foo.class);


                  This can be solved by either making the logger static or simply by moving it into the actual function(s).






                  share|improve this answer




















                  • 4





                    Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                    – christopher
                    Nov 19 '14 at 20:54






                  • 1





                    another way to solve it, is by adding transient modifier to the field

                    – gawi
                    Nov 17 '16 at 16:03











                  • logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                    – stolsvik
                    Apr 19 '18 at 9:42













                  24












                  24








                  24







                  I had this problem when I had a Log4J logger as a class property, such as:



                  private Logger logger = Logger.getLogger(Foo.class);


                  This can be solved by either making the logger static or simply by moving it into the actual function(s).






                  share|improve this answer















                  I had this problem when I had a Log4J logger as a class property, such as:



                  private Logger logger = Logger.getLogger(Foo.class);


                  This can be solved by either making the logger static or simply by moving it into the actual function(s).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 30 '13 at 19:14









                  Benjamin

                  16.4k30129237




                  16.4k30129237










                  answered Jan 28 '13 at 22:02









                  ZarZar

                  3,64464371




                  3,64464371







                  • 4





                    Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                    – christopher
                    Nov 19 '14 at 20:54






                  • 1





                    another way to solve it, is by adding transient modifier to the field

                    – gawi
                    Nov 17 '16 at 16:03











                  • logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                    – stolsvik
                    Apr 19 '18 at 9:42












                  • 4





                    Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                    – christopher
                    Nov 19 '14 at 20:54






                  • 1





                    another way to solve it, is by adding transient modifier to the field

                    – gawi
                    Nov 17 '16 at 16:03











                  • logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                    – stolsvik
                    Apr 19 '18 at 9:42







                  4




                  4





                  Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                  – christopher
                  Nov 19 '14 at 20:54





                  Absolutely great catch. That self reference to the class obviously not liked by GSON at all. Saved me a lot of headaches! +1

                  – christopher
                  Nov 19 '14 at 20:54




                  1




                  1





                  another way to solve it, is by adding transient modifier to the field

                  – gawi
                  Nov 17 '16 at 16:03





                  another way to solve it, is by adding transient modifier to the field

                  – gawi
                  Nov 17 '16 at 16:03













                  logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                  – stolsvik
                  Apr 19 '18 at 9:42





                  logger should mostly be static. Otherwise you will incur the cost of getting that Logger instance for each object creation, which is probably not what you want. (The cost isn't trivial)

                  – stolsvik
                  Apr 19 '18 at 9:42











                  16














                  If you're using Realm and you get this error, and the object giving the trouble extends RealmObject, don't forget to do realm.copyFromRealm(myObject) to create a copy without all the Realm bindings before passing through to GSON for serialization.



                  I'd missed doing this for just one amongst a bunch of objects being copied... took me ages to realise as the stack trace doesn't name the object class/type. Thing is, the issue is caused by a circular reference, but it's a circular reference somewhere in the RealmObject base class, not your own subclass, which makes it harder to spot!






                  share|improve this answer

























                  • That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                    – Ricardo Mutti
                    May 25 '17 at 20:11











                  • Using realm, that was exactly the solution that solves the problem, thanks

                    – Jude Fernandes
                    Oct 20 '18 at 8:18











                  • You saved my time !!! thank you

                    – Amjad Tubasi
                    Apr 20 at 23:47















                  16














                  If you're using Realm and you get this error, and the object giving the trouble extends RealmObject, don't forget to do realm.copyFromRealm(myObject) to create a copy without all the Realm bindings before passing through to GSON for serialization.



                  I'd missed doing this for just one amongst a bunch of objects being copied... took me ages to realise as the stack trace doesn't name the object class/type. Thing is, the issue is caused by a circular reference, but it's a circular reference somewhere in the RealmObject base class, not your own subclass, which makes it harder to spot!






                  share|improve this answer

























                  • That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                    – Ricardo Mutti
                    May 25 '17 at 20:11











                  • Using realm, that was exactly the solution that solves the problem, thanks

                    – Jude Fernandes
                    Oct 20 '18 at 8:18











                  • You saved my time !!! thank you

                    – Amjad Tubasi
                    Apr 20 at 23:47













                  16












                  16








                  16







                  If you're using Realm and you get this error, and the object giving the trouble extends RealmObject, don't forget to do realm.copyFromRealm(myObject) to create a copy without all the Realm bindings before passing through to GSON for serialization.



                  I'd missed doing this for just one amongst a bunch of objects being copied... took me ages to realise as the stack trace doesn't name the object class/type. Thing is, the issue is caused by a circular reference, but it's a circular reference somewhere in the RealmObject base class, not your own subclass, which makes it harder to spot!






                  share|improve this answer















                  If you're using Realm and you get this error, and the object giving the trouble extends RealmObject, don't forget to do realm.copyFromRealm(myObject) to create a copy without all the Realm bindings before passing through to GSON for serialization.



                  I'd missed doing this for just one amongst a bunch of objects being copied... took me ages to realise as the stack trace doesn't name the object class/type. Thing is, the issue is caused by a circular reference, but it's a circular reference somewhere in the RealmObject base class, not your own subclass, which makes it harder to spot!







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 17 '17 at 15:21

























                  answered Sep 23 '16 at 22:36









                  BreenoBreeno

                  2,15312123




                  2,15312123












                  • That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                    – Ricardo Mutti
                    May 25 '17 at 20:11











                  • Using realm, that was exactly the solution that solves the problem, thanks

                    – Jude Fernandes
                    Oct 20 '18 at 8:18











                  • You saved my time !!! thank you

                    – Amjad Tubasi
                    Apr 20 at 23:47

















                  • That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                    – Ricardo Mutti
                    May 25 '17 at 20:11











                  • Using realm, that was exactly the solution that solves the problem, thanks

                    – Jude Fernandes
                    Oct 20 '18 at 8:18











                  • You saved my time !!! thank you

                    – Amjad Tubasi
                    Apr 20 at 23:47
















                  That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                  – Ricardo Mutti
                  May 25 '17 at 20:11





                  That's correct! In my case change my object list queried directly from realm to ArrayList<Image> copyList = new ArrayList<>(); for(Image image : images) copyList.add(realm.copyFromRealm(image));

                  – Ricardo Mutti
                  May 25 '17 at 20:11













                  Using realm, that was exactly the solution that solves the problem, thanks

                  – Jude Fernandes
                  Oct 20 '18 at 8:18





                  Using realm, that was exactly the solution that solves the problem, thanks

                  – Jude Fernandes
                  Oct 20 '18 at 8:18













                  You saved my time !!! thank you

                  – Amjad Tubasi
                  Apr 20 at 23:47





                  You saved my time !!! thank you

                  – Amjad Tubasi
                  Apr 20 at 23:47











                  11














                  As SLaks said StackOverflowError happen if you have circular reference in your object.



                  To fix it you could use TypeAdapter for your object.



                  For example, if you need only generate String from your object you could use adapter like this:



                  class MyTypeAdapter<T> extends TypeAdapter<T> 
                  public T read(JsonReader reader) throws IOException
                  return null;


                  public void write(JsonWriter writer, T obj) throws IOException
                  if (obj == null)
                  writer.nullValue();
                  return;

                  writer.value(obj.toString());




                  and register it like this:



                  Gson gson = new GsonBuilder()
                  .registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>())
                  .create();


                  or like this, if you have interface and want to use adapter for all its subclasses:



                  Gson gson = new GsonBuilder()
                  .registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>())
                  .create();





                  share|improve this answer



























                    11














                    As SLaks said StackOverflowError happen if you have circular reference in your object.



                    To fix it you could use TypeAdapter for your object.



                    For example, if you need only generate String from your object you could use adapter like this:



                    class MyTypeAdapter<T> extends TypeAdapter<T> 
                    public T read(JsonReader reader) throws IOException
                    return null;


                    public void write(JsonWriter writer, T obj) throws IOException
                    if (obj == null)
                    writer.nullValue();
                    return;

                    writer.value(obj.toString());




                    and register it like this:



                    Gson gson = new GsonBuilder()
                    .registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>())
                    .create();


                    or like this, if you have interface and want to use adapter for all its subclasses:



                    Gson gson = new GsonBuilder()
                    .registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>())
                    .create();





                    share|improve this answer

























                      11












                      11








                      11







                      As SLaks said StackOverflowError happen if you have circular reference in your object.



                      To fix it you could use TypeAdapter for your object.



                      For example, if you need only generate String from your object you could use adapter like this:



                      class MyTypeAdapter<T> extends TypeAdapter<T> 
                      public T read(JsonReader reader) throws IOException
                      return null;


                      public void write(JsonWriter writer, T obj) throws IOException
                      if (obj == null)
                      writer.nullValue();
                      return;

                      writer.value(obj.toString());




                      and register it like this:



                      Gson gson = new GsonBuilder()
                      .registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>())
                      .create();


                      or like this, if you have interface and want to use adapter for all its subclasses:



                      Gson gson = new GsonBuilder()
                      .registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>())
                      .create();





                      share|improve this answer













                      As SLaks said StackOverflowError happen if you have circular reference in your object.



                      To fix it you could use TypeAdapter for your object.



                      For example, if you need only generate String from your object you could use adapter like this:



                      class MyTypeAdapter<T> extends TypeAdapter<T> 
                      public T read(JsonReader reader) throws IOException
                      return null;


                      public void write(JsonWriter writer, T obj) throws IOException
                      if (obj == null)
                      writer.nullValue();
                      return;

                      writer.value(obj.toString());




                      and register it like this:



                      Gson gson = new GsonBuilder()
                      .registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>())
                      .create();


                      or like this, if you have interface and want to use adapter for all its subclasses:



                      Gson gson = new GsonBuilder()
                      .registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>())
                      .create();






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 15 '13 at 17:11









                      borislubimovborislubimov

                      11113




                      11113





















                          6














                          My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.



                          With Gson you can mark the fields you do want to be included in json with @Expose like this:



                          @Expose
                          String myString; // will be serialized as myString


                          and create the gson object with:



                          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();


                          Circular references you just do not expose. That did the trick for me!






                          share|improve this answer

























                          • Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                            – jDub9
                            Aug 6 '18 at 11:49











                          • @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                            – ffonz
                            Aug 21 '18 at 13:15















                          6














                          My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.



                          With Gson you can mark the fields you do want to be included in json with @Expose like this:



                          @Expose
                          String myString; // will be serialized as myString


                          and create the gson object with:



                          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();


                          Circular references you just do not expose. That did the trick for me!






                          share|improve this answer

























                          • Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                            – jDub9
                            Aug 6 '18 at 11:49











                          • @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                            – ffonz
                            Aug 21 '18 at 13:15













                          6












                          6








                          6







                          My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.



                          With Gson you can mark the fields you do want to be included in json with @Expose like this:



                          @Expose
                          String myString; // will be serialized as myString


                          and create the gson object with:



                          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();


                          Circular references you just do not expose. That did the trick for me!






                          share|improve this answer















                          My answer is a little bit late, but I think this question doesn't have a good solution yet. I found it originally here.



                          With Gson you can mark the fields you do want to be included in json with @Expose like this:



                          @Expose
                          String myString; // will be serialized as myString


                          and create the gson object with:



                          Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();


                          Circular references you just do not expose. That did the trick for me!







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 13 '18 at 11:38

























                          answered Dec 6 '17 at 12:58









                          ffonzffonz

                          8491918




                          8491918












                          • Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                            – jDub9
                            Aug 6 '18 at 11:49











                          • @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                            – ffonz
                            Aug 21 '18 at 13:15

















                          • Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                            – jDub9
                            Aug 6 '18 at 11:49











                          • @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                            – ffonz
                            Aug 21 '18 at 13:15
















                          Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                          – jDub9
                          Aug 6 '18 at 11:49





                          Do you know if there is an annotation that does the opposite of this? There are like 4 fields I need to ignore and over 30 I need to include.

                          – jDub9
                          Aug 6 '18 at 11:49













                          @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                          – ffonz
                          Aug 21 '18 at 13:15





                          @jDub9 Sorry for my late answer, but I have been on holiday. Have a look at this answer. Hope it solves your problem

                          – ffonz
                          Aug 21 '18 at 13:15











                          2














                          This error is common when you have a logger in your super class. As @Zar suggested before, you can use static for your logger field, but this also works:



                          protected final transient Logger logger = Logger.getLogger(this.getClass());


                          P.S. probably it will work and with @Expose annotation check more about this here: https://stackoverflow.com/a/7811253/1766166






                          share|improve this answer





























                            2














                            This error is common when you have a logger in your super class. As @Zar suggested before, you can use static for your logger field, but this also works:



                            protected final transient Logger logger = Logger.getLogger(this.getClass());


                            P.S. probably it will work and with @Expose annotation check more about this here: https://stackoverflow.com/a/7811253/1766166






                            share|improve this answer



























                              2












                              2








                              2







                              This error is common when you have a logger in your super class. As @Zar suggested before, you can use static for your logger field, but this also works:



                              protected final transient Logger logger = Logger.getLogger(this.getClass());


                              P.S. probably it will work and with @Expose annotation check more about this here: https://stackoverflow.com/a/7811253/1766166






                              share|improve this answer















                              This error is common when you have a logger in your super class. As @Zar suggested before, you can use static for your logger field, but this also works:



                              protected final transient Logger logger = Logger.getLogger(this.getClass());


                              P.S. probably it will work and with @Expose annotation check more about this here: https://stackoverflow.com/a/7811253/1766166







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 12:10









                              Community

                              11




                              11










                              answered May 22 '15 at 7:09









                              zygimantuszygimantus

                              2,15012637




                              2,15012637





















                                  1














                                  I have the same problem. In my case the reason was that constructor of my serialized class take context variable, like this:



                                  public MetaInfo(Context context)


                                  When I delete this argument, error has gone.



                                  public MetaInfo()





                                  share|improve this answer


















                                  • 1





                                    I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                    – user802467
                                    Nov 4 '14 at 23:22











                                  • @user802467 do you mean android service?

                                    – Preetam
                                    May 2 '16 at 7:43















                                  1














                                  I have the same problem. In my case the reason was that constructor of my serialized class take context variable, like this:



                                  public MetaInfo(Context context)


                                  When I delete this argument, error has gone.



                                  public MetaInfo()





                                  share|improve this answer


















                                  • 1





                                    I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                    – user802467
                                    Nov 4 '14 at 23:22











                                  • @user802467 do you mean android service?

                                    – Preetam
                                    May 2 '16 at 7:43













                                  1












                                  1








                                  1







                                  I have the same problem. In my case the reason was that constructor of my serialized class take context variable, like this:



                                  public MetaInfo(Context context)


                                  When I delete this argument, error has gone.



                                  public MetaInfo()





                                  share|improve this answer













                                  I have the same problem. In my case the reason was that constructor of my serialized class take context variable, like this:



                                  public MetaInfo(Context context)


                                  When I delete this argument, error has gone.



                                  public MetaInfo()






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jun 20 '14 at 4:21









                                  DenisDenis

                                  4591411




                                  4591411







                                  • 1





                                    I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                    – user802467
                                    Nov 4 '14 at 23:22











                                  • @user802467 do you mean android service?

                                    – Preetam
                                    May 2 '16 at 7:43












                                  • 1





                                    I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                    – user802467
                                    Nov 4 '14 at 23:22











                                  • @user802467 do you mean android service?

                                    – Preetam
                                    May 2 '16 at 7:43







                                  1




                                  1





                                  I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                  – user802467
                                  Nov 4 '14 at 23:22





                                  I encountered this issue when passing service object reference as context. Fix was to make the context variable static in the class that uses gson.toJson(this).

                                  – user802467
                                  Nov 4 '14 at 23:22













                                  @user802467 do you mean android service?

                                  – Preetam
                                  May 2 '16 at 7:43





                                  @user802467 do you mean android service?

                                  – Preetam
                                  May 2 '16 at 7:43











                                  1














                                  Edit: Sorry for my bad, this is my first answer. Thanks for your advises.



                                  I create my own Json Converter



                                  The main solution I used is to create a parents object set for each object reference. If a sub-reference points to existed parent object, it will discard.
                                  Then I combine with an extra solution, limiting the reference time to avoid infinitive loop in bi-directional relationship between entities.



                                  My description is not too good, hope it helps you guys.



                                  This is my first contribution to Java community (solution to your problem). You can check it out ;)
                                  There is a README.md file
                                  https://github.com/trannamtrung1st/TSON






                                  share|improve this answer




















                                  • 2





                                    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                    – Paul Roub
                                    Jul 23 '18 at 4:13






                                  • 2





                                    Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                    – Shree
                                    Jul 23 '18 at 4:14











                                  • Thanks so much. I had edit my answer. Hope it would be fine :D

                                    – Trần Nam Trung
                                    Jul 23 '18 at 4:26











                                  • Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                    – LAD
                                    Jul 23 '18 at 4:42















                                  1














                                  Edit: Sorry for my bad, this is my first answer. Thanks for your advises.



                                  I create my own Json Converter



                                  The main solution I used is to create a parents object set for each object reference. If a sub-reference points to existed parent object, it will discard.
                                  Then I combine with an extra solution, limiting the reference time to avoid infinitive loop in bi-directional relationship between entities.



                                  My description is not too good, hope it helps you guys.



                                  This is my first contribution to Java community (solution to your problem). You can check it out ;)
                                  There is a README.md file
                                  https://github.com/trannamtrung1st/TSON






                                  share|improve this answer




















                                  • 2





                                    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                    – Paul Roub
                                    Jul 23 '18 at 4:13






                                  • 2





                                    Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                    – Shree
                                    Jul 23 '18 at 4:14











                                  • Thanks so much. I had edit my answer. Hope it would be fine :D

                                    – Trần Nam Trung
                                    Jul 23 '18 at 4:26











                                  • Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                    – LAD
                                    Jul 23 '18 at 4:42













                                  1












                                  1








                                  1







                                  Edit: Sorry for my bad, this is my first answer. Thanks for your advises.



                                  I create my own Json Converter



                                  The main solution I used is to create a parents object set for each object reference. If a sub-reference points to existed parent object, it will discard.
                                  Then I combine with an extra solution, limiting the reference time to avoid infinitive loop in bi-directional relationship between entities.



                                  My description is not too good, hope it helps you guys.



                                  This is my first contribution to Java community (solution to your problem). You can check it out ;)
                                  There is a README.md file
                                  https://github.com/trannamtrung1st/TSON






                                  share|improve this answer















                                  Edit: Sorry for my bad, this is my first answer. Thanks for your advises.



                                  I create my own Json Converter



                                  The main solution I used is to create a parents object set for each object reference. If a sub-reference points to existed parent object, it will discard.
                                  Then I combine with an extra solution, limiting the reference time to avoid infinitive loop in bi-directional relationship between entities.



                                  My description is not too good, hope it helps you guys.



                                  This is my first contribution to Java community (solution to your problem). You can check it out ;)
                                  There is a README.md file
                                  https://github.com/trannamtrung1st/TSON







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jul 23 '18 at 4:24

























                                  answered Jul 23 '18 at 4:11









                                  Trần Nam TrungTrần Nam Trung

                                  2614




                                  2614







                                  • 2





                                    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                    – Paul Roub
                                    Jul 23 '18 at 4:13






                                  • 2





                                    Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                    – Shree
                                    Jul 23 '18 at 4:14











                                  • Thanks so much. I had edit my answer. Hope it would be fine :D

                                    – Trần Nam Trung
                                    Jul 23 '18 at 4:26











                                  • Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                    – LAD
                                    Jul 23 '18 at 4:42












                                  • 2





                                    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                    – Paul Roub
                                    Jul 23 '18 at 4:13






                                  • 2





                                    Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                    – Shree
                                    Jul 23 '18 at 4:14











                                  • Thanks so much. I had edit my answer. Hope it would be fine :D

                                    – Trần Nam Trung
                                    Jul 23 '18 at 4:26











                                  • Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                    – LAD
                                    Jul 23 '18 at 4:42







                                  2




                                  2





                                  A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                  – Paul Roub
                                  Jul 23 '18 at 4:13





                                  A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.

                                  – Paul Roub
                                  Jul 23 '18 at 4:13




                                  2




                                  2





                                  Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                  – Shree
                                  Jul 23 '18 at 4:14





                                  Self Promotion Just linking to your own library or tutorial is not a good answer. Linking to it, explaining why it solves the problem, providing code on how to do so and disclaiming that you wrote it makes for a better answer. See: What signifies “Good” self promotion?

                                  – Shree
                                  Jul 23 '18 at 4:14













                                  Thanks so much. I had edit my answer. Hope it would be fine :D

                                  – Trần Nam Trung
                                  Jul 23 '18 at 4:26





                                  Thanks so much. I had edit my answer. Hope it would be fine :D

                                  – Trần Nam Trung
                                  Jul 23 '18 at 4:26













                                  Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                  – LAD
                                  Jul 23 '18 at 4:42





                                  Similar to what the other commenters said, it is preferred that you show the most important parts of your code in your post. Also, you don't need to apologize for mistakes in your answer.

                                  – LAD
                                  Jul 23 '18 at 4:42











                                  0














                                  In Android, gson stack overflow turned out to be the declaration of a Handler. Moved it to a class that isn't being deserialized.



                                  Based on Zar's recommendation, I made the the handler static when this happened in another section of code. Making the handler static worked as well.






                                  share|improve this answer





























                                    0














                                    In Android, gson stack overflow turned out to be the declaration of a Handler. Moved it to a class that isn't being deserialized.



                                    Based on Zar's recommendation, I made the the handler static when this happened in another section of code. Making the handler static worked as well.






                                    share|improve this answer



























                                      0












                                      0








                                      0







                                      In Android, gson stack overflow turned out to be the declaration of a Handler. Moved it to a class that isn't being deserialized.



                                      Based on Zar's recommendation, I made the the handler static when this happened in another section of code. Making the handler static worked as well.






                                      share|improve this answer















                                      In Android, gson stack overflow turned out to be the declaration of a Handler. Moved it to a class that isn't being deserialized.



                                      Based on Zar's recommendation, I made the the handler static when this happened in another section of code. Making the handler static worked as well.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jun 4 '13 at 22:16

























                                      answered May 1 '13 at 20:33









                                      DanDan

                                      42569




                                      42569





















                                          0














                                          BomItem refers to BOMModule (Collection<BomModule> modules), and BOMModule refers to BOMItem (Collection<BomItem> items). Gson library doesn't like circular references. Remove this circular dependency from your class. I too had faced same issue in the past with gson lib.






                                          share|improve this answer



























                                            0














                                            BomItem refers to BOMModule (Collection<BomModule> modules), and BOMModule refers to BOMItem (Collection<BomItem> items). Gson library doesn't like circular references. Remove this circular dependency from your class. I too had faced same issue in the past with gson lib.






                                            share|improve this answer

























                                              0












                                              0








                                              0







                                              BomItem refers to BOMModule (Collection<BomModule> modules), and BOMModule refers to BOMItem (Collection<BomItem> items). Gson library doesn't like circular references. Remove this circular dependency from your class. I too had faced same issue in the past with gson lib.






                                              share|improve this answer













                                              BomItem refers to BOMModule (Collection<BomModule> modules), and BOMModule refers to BOMItem (Collection<BomItem> items). Gson library doesn't like circular references. Remove this circular dependency from your class. I too had faced same issue in the past with gson lib.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 27 '15 at 4:50









                                              Binita BharatiBinita Bharati

                                              1,7161715




                                              1,7161715





















                                                  0














                                                  I had this problem occur for me when I put:



                                                  Logger logger = Logger.getLogger( this.getClass().getName() );


                                                  in my object...which made perfect sense after an hour or so of debugging!






                                                  share|improve this answer



























                                                    0














                                                    I had this problem occur for me when I put:



                                                    Logger logger = Logger.getLogger( this.getClass().getName() );


                                                    in my object...which made perfect sense after an hour or so of debugging!






                                                    share|improve this answer

























                                                      0












                                                      0








                                                      0







                                                      I had this problem occur for me when I put:



                                                      Logger logger = Logger.getLogger( this.getClass().getName() );


                                                      in my object...which made perfect sense after an hour or so of debugging!






                                                      share|improve this answer













                                                      I had this problem occur for me when I put:



                                                      Logger logger = Logger.getLogger( this.getClass().getName() );


                                                      in my object...which made perfect sense after an hour or so of debugging!







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Mar 12 '18 at 17:48









                                                      keespkeesp

                                                      1569




                                                      1569





















                                                          0














                                                          For Android users, you cannot serialize a Bundle due to a self-reference to Bundle causing a StackOverflowError.



                                                          To serialize a bundle, register a BundleTypeAdapterFactory.






                                                          share|improve this answer



























                                                            0














                                                            For Android users, you cannot serialize a Bundle due to a self-reference to Bundle causing a StackOverflowError.



                                                            To serialize a bundle, register a BundleTypeAdapterFactory.






                                                            share|improve this answer

























                                                              0












                                                              0








                                                              0







                                                              For Android users, you cannot serialize a Bundle due to a self-reference to Bundle causing a StackOverflowError.



                                                              To serialize a bundle, register a BundleTypeAdapterFactory.






                                                              share|improve this answer













                                                              For Android users, you cannot serialize a Bundle due to a self-reference to Bundle causing a StackOverflowError.



                                                              To serialize a bundle, register a BundleTypeAdapterFactory.







                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Dec 31 '18 at 16:16









                                                              Cord RehnCord Rehn

                                                              6491012




                                                              6491012





















                                                                  0














                                                                  Avoid unnecessary workarounds, like setting values to null or making fields transient. The right way to do this, is to annotate one of the fields with @Expose and then tell Gson to serialize only the fields with the annotation:



                                                                  private Collection<BomModule> parentModules;
                                                                  @Expose
                                                                  private Collection<BomModule> subModules;

                                                                  ...
                                                                  Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();





                                                                  share|improve this answer



























                                                                    0














                                                                    Avoid unnecessary workarounds, like setting values to null or making fields transient. The right way to do this, is to annotate one of the fields with @Expose and then tell Gson to serialize only the fields with the annotation:



                                                                    private Collection<BomModule> parentModules;
                                                                    @Expose
                                                                    private Collection<BomModule> subModules;

                                                                    ...
                                                                    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();





                                                                    share|improve this answer

























                                                                      0












                                                                      0








                                                                      0







                                                                      Avoid unnecessary workarounds, like setting values to null or making fields transient. The right way to do this, is to annotate one of the fields with @Expose and then tell Gson to serialize only the fields with the annotation:



                                                                      private Collection<BomModule> parentModules;
                                                                      @Expose
                                                                      private Collection<BomModule> subModules;

                                                                      ...
                                                                      Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();





                                                                      share|improve this answer













                                                                      Avoid unnecessary workarounds, like setting values to null or making fields transient. The right way to do this, is to annotate one of the fields with @Expose and then tell Gson to serialize only the fields with the annotation:



                                                                      private Collection<BomModule> parentModules;
                                                                      @Expose
                                                                      private Collection<BomModule> subModules;

                                                                      ...
                                                                      Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Feb 12 at 22:49









                                                                      Ismael SarmentoIsmael Sarmento

                                                                      17211




                                                                      17211





















                                                                          0














                                                                          I had a similar issue where the class had an InputStream variable which I didn't really have to persist. Hence changing it to Transient solved the issue.






                                                                          share|improve this answer



























                                                                            0














                                                                            I had a similar issue where the class had an InputStream variable which I didn't really have to persist. Hence changing it to Transient solved the issue.






                                                                            share|improve this answer

























                                                                              0












                                                                              0








                                                                              0







                                                                              I had a similar issue where the class had an InputStream variable which I didn't really have to persist. Hence changing it to Transient solved the issue.






                                                                              share|improve this answer













                                                                              I had a similar issue where the class had an InputStream variable which I didn't really have to persist. Hence changing it to Transient solved the issue.







                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Mar 24 at 5:11









                                                                              Kamalakannan VKamalakannan V

                                                                              11




                                                                              11



























                                                                                  draft saved

                                                                                  draft discarded
















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid


                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function ()
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10209959%2fgson-tojson-throws-stackoverflowerror%23new-answer', 'question_page');

                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                                  SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                                                  은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현