Unable to deserialize XML data when using List

57 Views Asked by At

I have springboot 3 application and using java 17. I was presented with an XML(below) to consume so I created classes to deserialize and set data on the POJO. I added jackson-dataformat-xml library and core to help me with it. But when I hit the API I get this error ::

Cannot construct instance of 'Data' (although at least one Creator exists): no String-argument contructor/factory method to deserialize from String value ('4') at [Source: (StringReader); line 3, clumn 31 ] through reference chain: com.TestDTO["data"]->java.util.ArrayList[0]) at com.fasterxml.jackson.databind.exc.MismatchedInputException.form(MismatchedInputException.java:63)

Here are my XML and POJO's

<TestDTO>
<data>
    <id>4</id>
    <name>hjashd</name>
</data>

<data>
    <id>13</id>
    <name>Jjiaj</name>
</data>
</TestDTO>
//TestDTO
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import java.util.List;

public class TestDTO {

    private List<Data> data;

    @JacksonXmlElementWrapper(useWrapping = false)
    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

}
//Data.class
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class Data {

    private String id;
    private String name;

    public Data() {
        // Default constructor
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

My controller method looks like this

@PutMapping(value='/getXMLData',consumes = MediaType.APPLICATION_XML_VALUE,produces = MediaType.APPLICATION.JSON)
public ResponseEntity digestXML(@RequestBody TestDTO test){
     //core services and return
}

I think I created the POJO just fine, this is how I usually did this when I used Java 8. I even changed the library and used jakarta.xml.bind-api but still get the same error. Before I didnt have degault constructor for Data which I added which chagned the error a bit no Creators , like default constructor exist) to (although at least one Creator exists).

I also tried to deserialize it separetely by getting String in controller and using the below method to deserialize, still the same error

private TestDTO deserializeXml(String xmlPayload) {
        ObjectMapper objectMapper = new XmlMapper();  
        try {
            return objectMapper.readValue(xmlPayload, TestDTO.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
}
0

There are 0 best solutions below