Json (fasterxml) stackoverflow exception

Sure thing, @JsonIgnore does the job. But what if we need ignored field in our JSON output?

The solution is very simple.

We annotate our 'guilty' field by @JsonManagedReference annotation on the one side of our relation (which means our @ManyToMany annotation).

And @JsonBackReference on the other side of relation (where @OneToMany has been placed).

And that's it. No more recursive loops.


Probably if you comment private Category parent; you will not have the StackOverflow. I've got the same problem in a project with circular dependencies.

The best way to solve this problem is to use the id of the parent instead of the Class like:

private Long parentId;

Edit:

The problem is with getParentChain() that is trying to be serialized. By adding @JsonIgnore before the method the problem was resolved.


One annotation solves your problem.

Add following annotation on class.

@JsonIdentityInfo(
      generator = ObjectIdGenerators.PropertyGenerator.class, 
      property = "id")

Other way is to annotate on Collections @JsonManagedReference for forward direction and @JsonBackReference. for backward direction in mapping.

example:

public class User{
    @JsonManagedReference
    @OneToMany(mappedBy = "user")
    Set<Address> s = new Hashset<>();
}

public class Address{
    @JsonBackReference
    @ManyToOne
    @JoinColumn
    User user;
}