我正在使用RestEasy,Jboss 7和EJB 3.1 . 我正在创建一个以JSON格式返回数据的RESTful Web服务 .
问题是我的一个实体上有一个 @ManyToOne
关系,这会在序列化过程中导致无限递归 . 我尝试使用Jackson的 @JsonIgnore
和 @JsonBackReference
注释来解决这个问题,但似乎它们被完全忽略了,无限递归仍在发生 .
这是我的用户类:
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;
}
}
这是我的角色类的一部分:
@JsonManagedReference("role-User")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "role")
public Set<User> getUsers() {
return this.users;
}
我已经读过某个地方,我应该用我的应用程序注册Jackson,以便能够使用常规的Jaxb注释,所以我创建了一个类
@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;
}
}
上面的问题是 JaxbAnnotationIntrospector()
已被弃用 .
请:
-
你知道 Jackson 注释被忽略的原因吗?
-
如何使用常规JAXB XML注释而不是Jackson?
-
我可以用什么代替
JaxbAnnotationIntrospector()
?
感谢,对这些问题的答案表示赞赏 .
Update:
现在我已经使用 jboss-deployment-structure.xml
排除 resteasy-jackson-provider
而我正在使用Jettison . 我还想知道我怎么能用 Jackson !
5 回答
这里的问题似乎与使用
Set<User>
而不是List<User>
有关 . 我有完全相同的问题,并从Set<User>
更改为List<User>
修复此问题,否则我总是得到 Jackson 的Infinite recursion
错误 . 我不知道这是不是 Jackson 的一个错误,或者你在使用Set
时必须提供其他一些注释等 .使用
import com.fasterxml.jackson.annotation.JsonBackReference;
而不是import org.codehaus.jackson.annotate.JsonBackReference;
.这对我来说是个问题 .
我有这个问题,并通过将我的构建(pom.xml)中的Jackson库版本从1.8.x更新到1.9.13来获得相同的代码 . 如果您使用的是maven,请编辑您的pom.xml以包含:
文档没有帮助,但似乎1.8.x版本不支持集合的后向引用 .
看,我有类似的东西,对我来说工作得很好......
这就是我对Entity1的看法
我不知道将注释移到顶部是否会改变任何东西,但这是我唯一能看到的东西......
干杯,
我使用的是spring 4.0.1,hibernate 4.3.5,jackson 1.9.2和STS IDE
我有相同的例外,但通过
@Transient
注意设置者解决了问题但是它工作正常这是我的实体类User.class
Telephone.class
关于将jackson注册到我的应用程序,我使用了xml配置
和mapper类