简体   繁体   中英

jaxb unmarshall list not working

Why in this example list of bazes is not unmarshalled correctly? Example results in a single Baz in the ArrayList with null properties. How to make it work correctly?

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;
        }
    }
}

The result is following

foo 1 null null 
1

You will need specify the wrapper object using @XmlElementWrapper and something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM