Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB does not serialize the full object graph

I have left out all other properties etc from the classes. None of the lists that I have in Question is serialized. I have added an example of the Answer list. The JSON reponse is fine except that "answers" is null. Why? The quiz object is fully initalized (yes, taken care of even though it is lazy loaded, custom code in repository layer) when I print it to console. I also used debugger to check.

@XmlRootElement
public class Quiz {

    private List<Question> questions;

    public List<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }
}

public class Question {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "QuestionId", nullable = false)
    @XmlElementWrapper(name = "answers")
    public List<Answer> getAnswers() {
        return answers;
    }

    public void setAnswers(final List<Answer> answers) {
        this.answers = answers;
    }
}

@Entity
@Table(name = "Answer")
public class Answer  {

}

EDIT:

Seems like the uncommented code is causing trouble. Switching the commenting makes the code working.

public void setAnswers(final List<Answer> answers) {

        //this.answers = answers;

        this.answers.clear();

        for (Answer answer : answers) {
            addAnswer(answer);
        }

    }

public void addAnswer(final Answer answer) {
    if (!(answers.contains(answer))) {
        checkThatOnlyOneAnswerMayBeCorrect(answer);
        answers.add(answer);
    }
}
like image 273
LuckyLuke Avatar asked Dec 18 '25 02:12

LuckyLuke


1 Answers

An important thing to note about JAXB (JSR-222) implementations is that if you have pre-initialized a List value that value will be used. For example if you your answers field is initialized as follow that instance of ArrayList will be used.

List<Answer> answers = new ArrayList<Answer>();

And if you initialize your answers field as follows that instance of LinkedList will be used.

List<Answer> answers = new LinkedList<Answer>();

That means the problem is with the following code. When you perform clear on the answers field you are also clearing the value being passed in since they are the same instance.

public void setAnswers(final List<Answer> answers) {

    //this.answers = answers;

    this.answers.clear();

    for (Answer answer : answers) {
        addAnswer(answer);
    }

}

For More Information

  • http://blog.bdoughan.com/2011/01/jaxb-and-choosing-list-implementation.html
like image 63
bdoughan Avatar answered Dec 19 '25 15:12

bdoughan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!