![](/img/trans.png)
[英]Why my jaxb2marshaller does not unmarshal what it marshalled before?
[英]Why my ArrayList is not marshalled with JAXB?
以下是用例:
@XmlRootElement
public class Book {
public String title;
public Book(String t) {
this.title = t;
}
}
@XmlRootElement
@XmlSeeAlso({Book.class})
public class Books extends ArrayList<Book> {
public Books() {
this.add(new Book("The Sign of the Four"));
}
}
然后,我正在做:
JAXBContext ctx = JAXBContext.newInstance(Books.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new Books(), System.out);
這就是我所看到的:
<?xml version="1.0"?>
<books/>
我的書在哪里? :)
要編組的元素必須是公共的,或者具有XMLElement anotation。 ArrayList類和您的類Books與這些規則中的任何一個都不匹配。 您必須定義一個方法來提供Book值,並對其進行分析。
在您的代碼上,只更改您的Books類添加“自我getter”方法:
@XmlRootElement
@XmlSeeAlso({Book.class})
public class Books extends ArrayList<Book> {
public Books() {
this.add(new Book("The Sign of the Four"));
}
@XmlElement(name = "book")
public List<Book> getBooks() {
return this;
}
}
當你運行你的編組代碼時,你會得到:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books><book><title>The Sign of the Four</title></book></books>
(為了清晰起見,我添加了換行符)
我認為你不能輕易地按原樣編組List
。 考慮使用另一個類來包裝列表。以下工作:
@XmlType
class Book {
public String title;
public Book() {
}
public Book(String t) {
this.title = t;
}
}
@XmlType
class Books extends ArrayList<Book> {
public Books() {
this.add(new Book("The Sign of the Four"));
}
}
@XmlRootElement(name = "books")
class Wrapper {
public Books book = new Books();
}
使用如下:
JAXBContext ctx = JAXBContext.newInstance(Wrapper.class);
Marshaller msh = ctx.createMarshaller();
msh.marshal(new Wrapper(), System.out);
它會產生這樣的結果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books><book><title>The Sign of the Four</title></book></books>
正如@Blaise和@musiKk所指出的那樣,最好只有一本Book of Book,並允許Books成為真正的根元素。 我不認為在我自己的代碼中擴展ArrayList是一個可接受的過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.