Open lalpert opened 8 years ago
Thanks for your suggestion, I will try to include this or something similar in 1.8.0 which I will be released around mid-oct.
Any progress with this issue? Is there some solution to handle cyclic reference and avoid stack overflow (other than remove one side of bidirectional reference)?
Thanks!
Is there some update about that? I've been looking for a elegant solution to this since ever and nothing found. For while..
Sorry I've been super busy and lost track of this. I'll think about something based on what @lalpert suggested and will reply back here before the end of the week with a timeline.
Would it work if I create an annotation to override the type adapter of a particular field in a class? For example
public class Person {
private int id;
private String name;
private House house;
}
public class House {
@TypeAdapter(SimplePersonAdapter.class)
private Person owner;
}
public class SimplePersonAdapter implements TypeAdapter<Person> {
//this class just serializes a simplified version of a Person object, for example it could just serialize the id
}
@interappcci, @lalpert I think I will include my suggestion in my previous comment since it solves also a different requirement that was raised to me the other day.
Does that work for both of you in regards to the circular reference problem?
I just need to cxclude a field at the second nested while serializing a object:
class User {
String name;
User createdBy;
}
class JsonRespWrap<D> {
int code;
User data;
public JsonRespWrap (D data ) {
this.data = data
this.code = 0
}
}
User user = userDao.findOne(1)
gson.toJson(new JsonRespWrap(user)); // data.createdBy.createdBy should be excluded but data.createdBy should be included
// here is the exclusion stratety
public class GsonExclusionStrategy implements ExclusionStrategy{
//...
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return true;
}
@Override
public boolean shouldSkipField(FieldAttributes f) {
//how to do whthout parent FieldAttributes (or a stack of FieldAttributeses) provided as parameter
}
}
Jackson has a solution to serializing classes with bidirection references using
@JsonIdentityInfo
(For example, see http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion#json-identity-info). This way, you can serialize either object, and rather than causing a stack overflow error, it will just include a reference back to the object already included in the serialization. It seems like Gson does not have a solution like that. Could that be added to gson-fire?