I'm working with RestEasy, Jboss 7 and EJB 3.1. I'm creating a RESTful web service that returns data in JSON format.
The problem is that I have a @ManyToOne
relationship on one of my entities which causes an infinite recursion during serialization. I tried using Jackson's @JsonIgnore
and @JsonBackReference
annotations to fix the problem but it seems as if they are being totally ignored and the infinite recursion is still occurring.
This is my User Class:
class User {
private String userId;
private Role role;
@Id
@Column(name = "\"UserId\"", unique = true, nullable = false, length = 30)
public String getUserId() {
return this.UserId;
}
public void setUserId(String UserId) {
this.UserId = UserId;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "\"RoleId\"", nullable = false)
//I have tried @JsonIgnore without @JsonBackReference
@JsonIgnore
//I have tried @JsonBackReference without @JsonIgnore
//Also I have tried @JsonBackReference and @JsonIgnore together
@JsonBackReference("role-User")
public Role getRole() {
return this.role;
}
}
This is a part of my Role Class:
@JsonManagedReference("role-User")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "role")
public Set<User> getUsers() {
return this.users;
}
I have read somewhere that I should register Jackson with my application to be able to use regular Jaxb annotation so I created a class
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
public JacksonContextResolver() {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.getDeserializationConfig().setAnnotationIntrospector(
introspector);
mapper.getSerializationConfig().setAnnotationIntrospector(introspector);
}
public ObjectMapper getContext(Class<?> objectType) {
return objectMapper;
}
}
The problem with the above being that JaxbAnnotationIntrospector()
is deprecated.
Please:
JaxbAnnotationIntrospector()
?An answer to any of these question is appreciated, thanks.
Update:
For now I have excluded resteasy-jackson-provider
using jboss-deployment-structure.xml
and I am using Jettison instead. I still want to know how could I use Jackson!
The problem here seems to be related to using Set<User>
instead of List<User>
. I had exactly the same problem and changing from Set<User>
to List<User>
fixed this, otherwise I always got Infinite recursion
error from Jackson. I don't know if this is really a bug in Jackson or do you have to provide some other annotations etc. when using Set
.