By default a JAXB (JSR-222) implementation examines the public accessor methods. You could add the Book
parameter on the List
in your get/set methods.
public List<Book> getBookslst() {
return bookslst;
}
public void setBookslst(List<Book> bookslst) {
this.bookslst = bookslst;
}
Alternatively you could specify the type of the property using the @XmlElement
annotation:
@XmlElement(type=Book.class)
public List getBookslst() {
return bookslst;
}
You could also specify that your JAXB implementation introspect the fields instead of the properties:
@XmlRootElement(name="lists")
@XmlAccessorType(XmlAccessType.FIELD)
public class BookLists {
List<Book> bookslst;
}
UPDATE
Is there any alternative way to add List instead of BookList in
Marshallar.Marshall?
You could create a generic List wrapper object that leveraged the @XmlAnyElement(lax=true)
annotation (see: http://blog.bdoughan.com/2010/08/using-xmlanyelement-to-build-generic.html). Then it cold handle a List
of anything annotated with @XmlRootElement
.
Lists
package forum12323397;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Lists<VALUE> {
private List<VALUE> values = new ArrayList<VALUE>();
@XmlAnyElement(lax=true)
public List<VALUE> getValues() {
return values;
}
}
Demo
package forum12323397;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Lists.class, Book.class);
Lists<Book> lists = new Lists<Book>();
Book book1 = new Book();
book1.setTitle("A Book");
book1.setYear(2001);
lists.getValues().add(book1);
Book book2 = new Book();
book2.setTitle("Another Book");
book2.setYear(2007);
lists.getValues().add(book2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(lists, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<lists>
<book>
<title>A Book</title>
<year>2001</year>
</book>
<book>
<title>Another Book</title>
<year>2007</year>
</book>
</lists>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…