简体   繁体   中英

How to get around circular references when using Gson?

I am building an Android application, in which I am using Gson to store Object data. I have a type Goal which I am using which has the following properties:

private long id;
private String goalName;
private boolean isMainGoal;
private Goal upperLevelGoal;
private Goal mainGoal;
private ArrayList<Goal> subGoals;
private int goalLevel;
private String textViewSubGoalLine;
private ArrayList<UrlComplex> sitesWithinGoal;

When using Gson's toJson() method, I get a StackOverflowError . From what I have read this is because Gson cannot handle circular references -- that is, it cannot perform toJson() on my Goal or ArrayList<Goal> properties.

I understand that I can somehow use TypeToken to get around this issue. ( gson.toJson() throws StackOverflowError ) However, I have read the manual ( http://google-gson.googlecode.com/svn/tags/1.1.1/docs/javadocs/com/google/gson/reflect/TypeToken.html ) and I don't really understand how it can be used to do so.

Does anyone know a way to get around using circular references so I can store info in JSON via Gson?

TypeToken won't help, its not made for that. If you want to handle circular references in Gson, you will need a TypeAdapterFactory , but its not simple.

A better approach is probably to parse your JSon with Jackson (but I actually never used this functionality) : http://wiki.fasterxml.com/JacksonFeatureBiDirReferences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM