如何使用嵌套列表反序列化xml?

时间:2018-07-04 11:06:22

标签: java xml spring jackson jaxb

如何读取包含嵌套列表的xml响应? 以下内容不起作用,表示嵌套列表始终为空。为什么?

    JacksonXmlModule xmlMod = new JacksonXmlModule();
    xmlMod.setDefaultUseWrapper(false);

    ObjectMapper m = (new Jackson2ObjectMapperBuilder())
            .createXmlMapper(true)
            .modules(xmlMod, new JaxbAnnotationModule())
            .build();


    PersonResponse rsp = m.readValue(ReaderUtil.read("person.xml"), PersonResponse.class)

//all fields having getter + setter, omitted for readability
@XmlRootElement
public class PersonResponse {
    @XmlElement(required = true)
    private Persons persons;

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Persons {
        @XmlElement(required = true)
        List<Person> person;

        @XmlAccessorType(XmlAccessType.FIELD)
        public static class Person {
            @XmlAttribute(name="firstname", required=true)
            private String firstname;
        }
    }
}

person.xml:

<response>
    <persons>
        <person firstname="test" />
        <person firstname="john" />
    </persons>
</response>

结果:person列表在响应对象中始终为空。为什么?

0 个答案:

没有答案