I'm trying to marshall multiple objects e.g. Book
added into BookLists
via setBookslst()
. I begin using this JAXBContext
setup:
jaxbContext = JAXBContext.newInstance(BookLists.class);
and
jaxbMarshaller.marshal(lists, result);
I'm given the following runtime exception however:
javax.xml.bind.JAXBException: com.jaxb.example.marshall.Book nor any of its super class is known to this context]
My types are defined as follows.
Book :-
@XmlRootElement(name="book")
public class Book {
private String title;
private int year;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
BookList :-
@XmlRootElement(name="lists")
public class BookLists {
List<Book> bookslst;
public List getBookslst() {
return bookslst;
}
public void setBookslst(List bookslst) {
this.bookslst = bookslst;
}
}
Marshall Code:-
Book book;
BookLists lists=new BookLists();
List lst=new ArrayList();
book = new Book();
book.setTitle("Book title");
book.setYear(2010);
lst.add(book);
book = new Book();
book.setTitle("Book title1");
book.setYear(2011);
lst.add(book);
lists.setBookslst(lst);
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(BookLists.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter result = new StringWriter();
jaxbMarshaller.marshal(lists, result);
String xml = result.toString();
System.out.println(xml);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to put @XMLSeeAlso
annotations(Ref:- JAXB Exception: Class not known to this context). This annotation is not available in my version.
Try adding both classes to your JAXBContext.newInstance call.
Using your classes this works:
Output:
Add the annotation @XmlSeeAlso(value = {Book.class }) to the BookList class. Should work now.
Use
Instead of :
Also Define BoolList as below:
By default a JAXB (JSR-222) implementation examines the public accessor methods. You could add the
Book
parameter on theList
in your get/set methods.Alternatively you could specify the type of the property using the
@XmlElement
annotation:You could also specify that your JAXB implementation introspect the fields instead of the properties:
UPDATE
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 aList
of anything annotated with@XmlRootElement
.Lists
Demo
Output
A Working Example I have:
1) XML:
2) Java classes:
Bookstore
3) Book
4) Main