'Converting xml string to Object class using jackson
Can someone please help in deserializing xml string : List<A> to Object.class using jackson in java.Xml looks like :
<list> <A><id>1</id><name>Jeff</name> <id>2</id><name>John</name> </A>
It returns a HashMap object if I convert it to Object.class . I have created a utility function XMLToObject which returns Object class. This will be typcasted on the caller function end to get the required type of Object.
public Object XMLtoObject(String xml){
return mapper.readValue(xml,Object.class)
}
But if I use List.class in place of Object.class it deserializes it to list of hashmaps.
public Object XMLtoObject(String xml){
return mapper.readValue(xml,List.class)
}
I am looking a way to convert it into Object.class which I can typecast on caller function . Is that possible in jackson ? I know we can do it through xstream
Solution 1:[1]
The problem with List.class is that it doesn't have any information about its elements. You need one of the overloaded readValue methods. For instance, using TypeReference:
return mapper.readValue(xml, new TypeReference<List<Object>>() {});
This creates an anonymous sub class of TypeReference, from which the complete generic type (List<Object>) can be read by Jackson. The result should therefore be a List<Object> instead of a List<HashMap>.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rob Spoor |
