gson.toJson() throws StackOverflowError

大城市里の小女人 提交于 2019-12-17 04:31:23

问题


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?


回答1:


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;



回答2:


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).




回答3:


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!




回答4:


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();



回答5:


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!




回答6:


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




回答7:


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()



回答8:


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




回答9:


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.




回答10:


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.




回答11:


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!




回答12:


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.




回答13:


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();



回答14:


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.



来源:https://stackoverflow.com/questions/10209959/gson-tojson-throws-stackoverflowerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!