如何反序列化 XML 并在给定元素后获取特定键的值

How to deserialize XML and get value of specific key after given element

XML喜欢:

<campaign>
    <id  type="integer">123</id>
    <name>campaign1</name>
    <description>campaign1</description>
    <flights  type="array">
        <flight>
            <id  type="integer">987</id>
            <name>flight1</name>
        </flight>
        <flight>
            <id  type="integer">3254</id>
            <name>flight2</name>
        </flight>
    </flights>
</campaign>

我想在 Flights 节点下获取数据。我正在使用 2.8.0 版本的 com.fasterxml.jackson.dataformat

我正在使用代码: 航班 class

@Getter
@JacksonXmlRootElement(localName = "flight")
public class Flight {
    @JsonProperty("id")
    private String id;
    @JsonProperty("name")
    private String name;
}

测试class:

ObjectMapper flightMapper = new XmlMapper();
flightMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Flight flight = flightMapper.readValue(xmlString, Flight.class);

但这总是给我广告系列的 ID 和名称。我得到的输出是

id = 123
name = campaign1

我也试过使用:

List<Flight> flights = flightMapper.readValue(xmlString, new TypeReference<List<Flight>>() {});

但这总是 returns null 值。 谁能帮帮我吗?我想用 idname.

获取 List<Flight> 对象

最简单的解决方案是创建包装器 class:

class Campaign {
    @JacksonXmlElementWrapper(localName = "flights")
    private List<Flight> flights;

    // getters, setters, toString
}

之后你可以反序列化如下:

List<Flight> flights = xmlMapper.readValue(xmlFile, Campaign.class).getFlights();