Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top