Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
Toni4780 Avatar asked Dec 31 '25 04:12

Toni4780


1 Answers

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

  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
  • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
like image 86
bdoughan Avatar answered Jan 02 '26 18:01

bdoughan