There have been many questions as to how why list types are not serialising, however I’m questioning what is a good practice to serve a list type of beans in a simple way.
So far I have been creating inner classes to support the wrapper, though I don’t like the plumbing as it were as I then need to do it for every pojo.
A customer class may look as follows:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
private int id;
private String name;
// field accessors
@XmlRootElement(name = "customers")
@XmlAccessorType(XmlAccessType.FIELD)
public static final class CustomerList {
private List<Customer> customer;
public CustomerList() {
this.customer = new ArrayList<>();
}
public DataList(List<Customer> list) {
this.customer = list;
}
// customer accessors.
}
}
I tried making a generic class like XmlList<T> and create new instances on return but JAXB appears to not like this.
I’m using this in a Spring/MVC RESTful application where I need to support both JSON and XML. My JSON should be represented as an array, which allows this method to easily facilitate both by placing the implementation inside the JSON call and then wrapping with the XML call.
Here comes how I do this.
Then you can make any required plural types of any singular types.
Maybe you don’t like that you should make all those plural classes for all singular types but it could be really helpful especially when you want to be look more nice to those client developers.
UPDATE per Brett Ryan’s comment
Here comes fully featured source codes.
You can see full mavenized project at http://code.google.com/p/jinahya/source/browse/trunk/com.googlecode.jinahya/stackoverflow/
JAXB doesn’t need the setter if you control to use fields not properties.
testing…
prints
UPDATE per Brett Ryan’s 2nd comment
When
Pluralannotated with@XmlRootElement.When
Pluralannotated with@XmlTransient.