Search code examples
javajacksonjackson-databindjackson-dataformat-xml

Deserialize XML element with attributes with no value using Jackson Java


I am trying to deserialize the following XML and I couldn't get the parameter param section deserialized.

<video src="https://google.com/sample.mp4">
    <param>s</param>
    <param>Y</param>
    <param>Z</param>
</video>

My model

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

import java.util.ArrayList;
import java.util.List;

public class Video {
    @JacksonXmlProperty(isAttribute = true)
    private String src;

    @JacksonXmlElementWrapper(localName = "param", useWrapping = false)
    private List<String> param = new ArrayList<>();

    public String getSrc() {
        return src;
    }

    public List<String> getParam() {
        return param;
    }

    public void setParam(List<String> param) {
        this.param = param;
    }
}

Output

{
    "src": "https://google.com/sample.mp4",
    "param": [
        "Z"
    ]
}

I am expecting the values of param to be something like

{
    "src": "https://google.com/sample.mp4",
    "param": [
        "s",
        "Y",
        "Z"
    ]
}

Java code

ObjectMapper mapper = new ObjectMapper(new XmlFactory());
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Video video = mapper.readValue(s, Video.class);
System.out.println(new ObjectMapper(new JsonFactory()).writeValueAsString(video));

Can someone help me getting it working. Thank you.


Solution

  • I used the following code and it worked for me,

    XmlMapper mapper = new XmlMapper();
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        Video video = mapper.readValue(s, Video.class);
        System.out.println(new ObjectMapper(new JsonFactory()).writeValueAsString(video));
    

    XmlMapper is frorm package com.fasterxml.jackson.dataformat.xml.XmlMapper

    Hope it helped you.