Reputation: 1467
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.
Upvotes: 1
Views: 2421
Reputation: 1206
You need to use:
@JacksonXmlProperty(localName = "param")
@JacksonXmlElementWrapper(useWrapping = false)
private List<String> param = new ArrayList<>();
and delete mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
as it only masks the issue.
This code worked for me:
XmlMapper mapper = new XmlMapper();
Video video = mapper.readValue(s, Video.class);
System.out.println(new ObjectMapper(new JsonFactory()).writeValueAsString(video));
Outputs: {"src":"https://google.com/sample.mp4","param":["s","Y","Z"]}
Upvotes: 2
Reputation: 703
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.
Upvotes: 1