Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

marshaling java objects instantiated from classes which implement interfaces with JAXB

How can we marshal objects into XML files using JAXB when we use interfaces for our classes? I have the following simple classes:

public interface IBook {

    public abstract String getName();

    public abstract void setName(String name);

}
@XmlRootElement
public class Book implements IBook {

    private String name;

    @Override
    @XmlElement(name ="BookTitle")
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }
}


@XmlRootElement
public class BookStore {

    @XmlElement(name ="BookStoreName")
    public String name;

    @XmlElementWrapper(name ="bookList")
    @XmlAnyElement
    public HashSet<IBook> books= new HashSet<IBook>();

    }

and when I try to marshal an object from BookStore into an XML file, I get the following error:

[com.sun.istack.internal.SAXException2: Weder class de.uni_paderborn.books.Book noch eine der zugehörigen Superklassen ist diesem Kontext bekannt.

javax.xml.bind.JAXBException: Weder class de.uni_paderborn.books.Book noch eine der zugehörigen Superklassen ist diesem Kontext bekannt.]

Sorry for the German error message, but my OS is German. This means that neither the class Book nor one of its superclasses is known in this context! Why do I get such an error?

like image 814
Anas Avatar asked Jan 17 '26 03:01

Anas


1 Answers

The problem is that you are missing @XmlSeeAlso in your BookStore class. Add it to your BookStore class like this

@XmlRootElement
@XmlSeeAlso({Book.class})
public class BookStore {

    @XmlElement(name = "BookStoreName")
    public String name;

    @XmlElementWrapper(name = "bookList")
    @XmlAnyElement
    public HashSet<IBook> books = new HashSet<IBook>();


    public static void main(String[] args) throws JAXBException {
        BookStore bookStore = new BookStore();
        bookStore.name = "FooBookStore";
        Book e = new Book();
        e.setName("Java");
        bookStore.books.add(e);

        /**
         * Create JAXB Context from the classes to be serialized
         */
        JAXBContext context = JAXBContext.newInstance(BookStore.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(bookStore, System.out);
    }
}

Outputs

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookStore>
    <BookStoreName>FooBookStore</BookStoreName>
    <bookList>
        <book>
            <BookTitle>Java</BookTitle>
        </book>
    </bookList>
</bookStore>
like image 132
sol4me Avatar answered Jan 19 '26 17:01

sol4me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!