【发布时间】:2013-12-14 14:48:36
【问题描述】:
我有一个带有两个实体的 javaEE 应用程序,它们在数据库中获得持久化。两个实体都有双向关联。
第一个实体:
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope=Child.class)
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch= FetchType.LAZY)
private Father father;
}
第二个实体
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id", scope=Father.class)
public class Father implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch= FetchType.LAZY)
private Child child;
}
两者都通过以下资源公开:
@Path("father")
@Stateless
public class FatherResource{
@Context
private UriInfo uri;
@Inject FatherDao fatherDao;
public FatherResource() {
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Father> getFathers() {
//TODO return proper representation object
return fatherDoa.getFathers();
}
}
还有一个 DAO,它只是从数据库中获取父对象。
现在的问题是,我得到了一个循环的 json 结构。 就像这样:
{ "id":"1", "child": {"id":"1", "father": {"id":"1", "child":{"id":"1", [...]
我只想见孩子一次。
我尝试使用:
@JsonIgnoreProperties({"child"}) //above the class
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") //above the class
@JsonIgnore //above the property
我想得到的是:
{ "id":"1", "child": {"id":"1"}}
我正在使用
JDK 7
JaxRS
Jackson
Hibernate/Eclipselink
Glassfish 4.0
另一个不起作用的测试:
@Entity
@JsonSerialize
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="id", scope=Object.class)
public class Father implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch= FetchType.LAZY)
private Child child;
}
ApplicationConfig.java:
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
// following code can be used to customize Jersey 2.0 JSON provider:
try {
Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
} //...
//..
beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="annotated">
</beans>
【问题讨论】:
-
您的问题是什么?特别是,您希望发生什么?
-
我想得到:{ "id":"1", "child": {"id":"1"}}
-
您尝试过 Jackson 的 ObjectIdentity 功能吗? wiki.fasterxml.com/JacksonFeatureObjectIdentity
-
好吧,这行不通。
-
如果您举例说明您尝试过的事情以及它们如何不起作用,这可能会有所帮助。
标签: json jakarta-ee jackson jax-rs java-ee-7