Search code examples
javaxmljacksonjackson-databindjackson-dataformat-xml

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


I have XML like:

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

I want to fetch data under Flights node. I'm using com.fasterxml.jackson.dataformat of 2.8.0 version.

I'm using code: Flight class

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

Test class:

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

But this always gives me id and name of campaign. Output that I get is

id = 123
name = campaign1

I also tried using:

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

But this always returns null value. Can anyone please help me? I want to fetch List<Flight> object with id and name.


Solution

  • The simplest solution is to create wrapper class:

    class Campaign {
        @JacksonXmlElementWrapper(localName = "flights")
        private List<Flight> flights;
    
        // getters, setters, toString
    }
    

    After that you can deserialise it as below:

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