代码之家  ›  专栏  ›  技术社区  ›  yegor256

为什么我的数组列表没有与JAXB一起编组?

  •  17
  • yegor256  · 技术社区  · 14 年前

    以下是用例:

    @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/>
    

    我的书在哪里?:)

    3 回复  |  直到 12 年前
        1
  •  15
  •   Tomas Narros    14 年前

    要封送的元素必须是公共的,或者具有xmlement anotation。arraylist类和您的类书籍不符合任何这些规则。 您必须定义一个方法来提供图书值,并对其进行说明。

    在代码中,只更改Books类,添加“self 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>
    

    (为了清晰起见,我加了一个换行符)

        2
  •  2
  •   musiKk    14 年前

    我觉得你不容易 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>
    
        3
  •  0
  •   Half_Duplex    12 年前

    正如@blaise和@musikk所指出的那样,最好只是在书中列出一个图书列表,并允许图书成为真正的根元素。在我自己的代码中,我不认为扩展arraylist是一个可接受的过程。