使用jaxb @XmlID和@XmlIDREF来解密复杂对象图.
public class JSONTestCase {
@XmlRootElement
public static final class Entity {
private String id;
private String someInfo;
private DetailEntity detail;
@XmlIDREF
private DetailEntity detailAgain;
public Entity(String id, String someInfo, DetailEntity detail) {
this.id = id;
this.someInfo = someInfo;
this.detail = detail;
this.detailAgain = detail;
}
// default constructor, getters, setters
}
public static final class DetailEntity {
@XmlID
private String id;
private String someDetailInfo;
// constructors, getters, setters
}
@Test
public void testMarshalling() throws JAXBException {
Entity e = new Entity( "42", "info", new DetailEntity("47","detailInfo") );
JAXBContext context = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[]{Entity.class}, null);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
m.marshal(e, System.out);
}
}
这将导致以下json-fragment
{
"detailAgain" : "47",
"detail" : {
"id" : "47",
"someDetailInfo" : "detailInfo"
},
"id" : "42",
"someInfo" : "info"
}
解组这个json将确保细节和detailAgain是相同的实例.
这两个注释是jaxb的一部分,所以它可以在Spring和java EE中工作.编组到json不是标准的一部分,所以我在这个例子中使用moxy.
更新
明确使用moxy在JAX-RS资源中不是必需的.以下剪辑完全在java-EE-7容器(glassfish 4.1.1)上运行,并导致以上json-fragment:
@Stateless
@Path("/entities")
public class EntityResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Entity getEntity() {
return new Entity( "42", "info", new DetailEntity("47","detailInfo") );
}
}