In the context of RestFul-Webservice (Jersey) I need to marshal / serialize the graph of objects in XML and JSON. For simplicity, I am trying to explain a problem with 2-3 classes:
Person.java
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Person { private String name;
House.java
@XmlAccessorType(XmlAccessType.FIELD) public class House {
Now when I serialize Person, the XML will look like this:
<people> <person> <name>Edward</name> <houses> <house> <name>MyAppartment</name> <location>London</location> </house> <house> <name>MySecondAppartment</name> <location>London</location> </house> </houses> </person> <person> <name>Thomas</name> <houses> <house> <name>MyAppartment</name> <location>London</location> </house> <house> <name>MySecondAppartment</name> <location>London</location> </house> </houses> </person> </people>
The problem here is that the same houses are listed several times. Now I am adding annotations without commenting on XmlIDREF and XmlID , which will cause the XML to look like the following:
<people> <person> <name>Edward</name> <houses> <house>MyAppartment</house> <house>MySecondAppartment</house> </houses> </person> <person> <name>Thomas</name> <houses> <house>MyAppartment</house> <house>MySecondAppartment</house> </houses> </person> </people>
While the first XML was too verbose, this was missing information. How can I create (and untie) something similar to:
<people> <person> <name>Edward</name> <houses> <house>MyAppartment</house> <house>MySecondAppartment</house> </houses> </person> <person> <name>Thomas</name> <houses> <house>MyAppartment</house> <house>MySecondAppartment</house> </houses> </person> <houses> <house> <name>MyAppartment</name> <location>London</location> </house> <house> <name>MySecondAppartment</name> <location>London</location> </house> </houses> </people>
The solution should be general, because I do not want to write additional classes for each new element in the object graph.
For completeness, here's a calm webservice:
@Path("rest/persons") public class TestService { @GET @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_JSON }) public Collection<Person> test() throws Exception { Collection<Person> persons = new ArrayList<Person>(); Collection<House> houses = new HashSet<House>(); houses.add(new House("MyAppartment", "London")); houses.add(new House("MySecondAppartment", "London")); persons.add(new Person("Thomas", houses)); persons.add(new Person("Edward", houses)); return persons; } }
Thanks in advance.