JsonMappingException: Infinite recursion on OneToMany Relationship in Objectify

625 views Asked by At

To serve a backend for an Android App i am using Google App Engine together with Objectify (4.0.3b).

On the backend I have a simple User Entity, which has a list of Users (friends) as relationship.

@Entity
public class User {

    @Id
    private String email;
    @Load
    private List<Ref<User>> friends = new ArrayList<Ref<User>>();

    private User() {
    }

    public List<User> getFriends() {
        ArrayList<User> friendList = new ArrayList<User>();
        for (Ref<User> ref : this.friends) {
            friendList.add(ref.get());
        }
        return friendList;
    }

    public void setFriends(List<User> friends) {
        List<Ref<User>> refs = new ArrayList<Ref<User>>();
        for (User user : friends) {
            refs.add(Ref.create(user));
        }
        this.friends = refs;
    }

}

Now when I have following Users stored in the Database for instance : user1 and user2:

user1 has user2 in his friend list and vice versa

When trying to fetch a User object (that has the above cycle reference) from my Endpoint, the Android client throws the following exception:

com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]...

In this post Infinite Recursion with Jackson JSON and Hibernate JPA issue they recommend to use @JsonIgnore on the field or the getter/setter method. But on the client side i need to access the friends list by these getter/setter methods (from the generated client library object), so this doesn't help me.

Another tip is to use @JsonManagedReference and @JsonBackReference, which in my case can't be applied since ManagedReference and BackReference would pointto the same friends field.

What I think could solve my Problem is the @JsonIdentityInfo Annotation which is available since Jackson 2.0.

My problem now is that I don't know how I can use this Annotation with Google App Engine. GAE uses jackson-core-asl-1.9.11, which unfortunately does not have the @JsonIdentityInfo, as it obviously is depending on a version below 2.0.

Does anybody know, how I can use the latest Jackson Version (2.4) in Google App Engine to use the @JsonIdentityInfo feature?

Or is there a better approach for my problem?

1

There are 1 answers

0
jirungaray On

The best approach would be to define a DTO class to use as a return parameter for your endpoint and use that to flatten the JSON response (meaning not sending the infinite loop of friend's friends).