Toni4780
Toni4780

Reputation: 453

Why is my List not serialized in JAXB?

I am new to using JAXB and I'm struggling with a problem right now. Perhaps you can help me.

I have the following code:

@XmlRootElement
public class Students implements Serializable{

private static final long serialVersionUID = 1L;

private List<Person> personList;
private int id;

// getters and setters for the attributes

}

and

 @XmlRootElement
 public class Person implements Serializable {

private static final long serialVersionUID = 1L;

private String name;
private int sex;

    //getters and setters for the attributes
 }

when I try to marshal Students this with JAXB, i only have the id-Element in the resulting string. I don't have the list (persons). Where is the problem here?

Upvotes: 3

Views: 4107

Answers (2)

bdoughan
bdoughan

Reputation: 148977

There isn't anything special you need to do to marshal List properties. Just make sure one of the following is true:

If you are using the JAXB reference implementation and have a getter for the List property but no setter, then you will need to annotate the getter with @XmlElement

@XmlRootElement
public class Students implements Serializable{

    private static final long serialVersionUID = 1L;

    private List<Person> personList;

    @XmlElement
    public List<Person> getPersonList() {
        return personList;
    }

}

If you don't have a public accesssor, make sure you are using field access:

@XmlRootElement
@XmlAccessorType(XmlAcceesType.FIELD)
public class Students implements Serializable{

    private static final long serialVersionUID = 1L;

    private List<Person> personList;

}

If you have a getter and setter for the List property then you don't need to do anything:

@XmlRootElement
public class Students implements Serializable{

    private static final long serialVersionUID = 1L;

    private List<Person> person = new ArrayList<Person>();

    public List<Person> getPersonList() {
        return person;
    }

    public void setPersonList(List<Person> personList) {
        this.person = personList;
    }

}

For More Information

Upvotes: 6

korifey
korifey

Reputation: 3509

Hm, try to mark class Person as @XmlType (not neccessary, I think) and all field of Students and Person classes as @XmlElement

Upvotes: 0

Related Questions