2017-02-27 68 views
0

爲什麼在這個例子中,bazes列表沒有正確解組?示例導致ArrayList中的單個Baz具有空屬性。如何使其正確工作?jaxb unmarshall list now working

public class Application { 

    private final static String FOO_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><FooBar><foo>foo</foo><bar>1</bar>" 
      + "<bazes><baz><baz1>baz11</baz1><baz2>baz12</baz2></baz><baz><baz1>baz21</baz1><baz2>baz22</baz2></baz></bazes>" 
      + "</FooBar>"; 

    public static void main(String[] args) throws JAXBException { 

     JAXBContext ctx = JAXBContext.newInstance(FooBar.class); 
     Unmarshaller u = ctx.createUnmarshaller(); 
     FooBar result = (FooBar) u.unmarshal(new ByteArrayInputStream(FOO_XML.getBytes())); 

     System.out.println(result); 
     System.out.println(result.bazes.size()); 
    } 

    @XmlRootElement(name = "FooBar") 
    @XmlAccessorType(XmlAccessType.FIELD) 
    public static class FooBar { 

     @XmlElement 
     private String foo; 
     @XmlElement 
     private int bar; 
     @XmlElement(name = "bazes") 
     public ArrayList<Baz> bazes; 

     @Override 
     public String toString() { 
      StringBuffer sb = new StringBuffer(); 
      sb.append(foo + " "); 
      sb.append(bar + " "); 
      for (Baz baz : bazes) { 
       sb.append(baz.baz1 + " " + baz.baz2 + " "); 
      } 
      return sb.toString(); 
     } 

     @XmlType 
     @XmlAccessorType(XmlAccessType.FIELD) 
     public static class Baz { 

      @XmlElement 
      private String baz1; 
      @XmlElement 
      private String baz2; 
     } 
    } 
} 

結果如下

foo 1 null null 
1 

回答

1

你需要指定使用@XmlElementWrapper和這樣的事情

@XmlElementWrapper(name = "bazes") 
@XmlElement(name = "baz", type = Baz.class) 
public ArrayList<Baz> bazes; 
+0

這工作完全包裝對象 –