Let's say my XML is :
<someObject>
<someArray>
<element>111</element>
<element>222</element>
</someArray>
</someObject>
Is there a Java built-in Type that I can use to deserialize this XML without requiring custom deserialization code?
For example, if I use a Map<Object, Object>
, only one element
is kept, the other one is overwritten! :
String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
Map<Object, Object> resultObj = getXmlMapper().readValue(xmlStr, new TypeReference<Map<Object, Object>>(){});
System.out.println(resultObj);
This prints :
{someArray={element=222}}
Is there any Type that Jackson understands and that can handle arrays correctly?
In your specific case you could use
new TypeReference<Map<Object, List>>
output : {someArray=[111, 222]}.
I would much prefer to use a proper structure if there is any more complexity to your XML.
@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
@JacksonXmlProperty(localName = "someArray")
List<String> someArray;
@Override
// for testing
public String toString() {
return someArray.toString();
}
}
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper map = new XmlMapper();
String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
SomeObject resultObj = map.readValue(xmlStr, new TypeReference<SomeObject>(){});
System.out.println(resultObj);
}
Output
[111, 222]
Alternatively use an array
@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
@JacksonXmlProperty(localName = "someArray")
String[] someArray;
@Override
public String toString() {
return Arrays.asList(someArray).toString();
}
}