You model works for me as is. See example below:
Demo
package forum13350129;
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Quiz.class);
Question question1 = new Question();
List<Answer> answers1 = new ArrayList();
answers1.add(new Answer());
answers1.add(new Answer());
question1.setAnswers(answers1);
Question question2 = new Question();
List<Answer> answers2 = new ArrayList();
answers2.add(new Answer());
answers2.add(new Answer());
question2.setAnswers(answers2);
Quiz quiz = new Quiz();
quiz.getQuestions().add(question1);
quiz.getQuestions().add(question2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(quiz, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<quiz>
<questions>
<answers/>
<answers/>
</questions>
<questions>
<answers/>
<answers/>
</questions>
</quiz>
UPDATE #1
What if you try to get it as JSON as I do?
This depends. JSON-binding is not part of the JAXB (JSR-222) specification. This means your environment is doing one of the following:
- Using a JAXB impl with a library like Jettison to produce JSON (see: http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html)
- Using a JSON-binding library (such as Jackson that has some JAXB annotation support)
- Using a JAXB impl such as EclipseLink MOXy that offers JSON binding (see: http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html).
Using EclipseLink JAXB (MOXy) as follows:
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.marshal(quiz, System.out);
Would produce the following JSON:
{
"quiz" : {
"questions" : [ {
"answers" : [ {
}, {
} ]
}, {
"answers" : [ {
}, {
} ]
} ]
}
}
UPDATE #2
I have fixed the issue with lazy loaded relationships. I am using
Hibernate.initialize in the repository. I am trying to return this
quiz object from the resource that I have. I am using JAX-RS.
I have seen people have problems marshalling Hibernate models to XML. I believe the issue was due to proxy objects that Hibernate uses. In the link below I suggested using an XmlAdapter
to convert between the proxy objects and the real ones and it was helpful.