Jackson xml lists deserialization recognized as duplicate keys

I am trying to convert xml to json using jackson-2.5.1

and jackson-dataformat-xml-2.5.1


The xml structure is received from the web server and is unknown, so I cannot have a Java class to represent the object, and I am trying to convert directly to TreeNode

using ObjectMapper.readTree

.
My problem is that Jackson doesn't understand lists. Only the last element of the list is required.
code:

String xml = "<root><name>john</name><list><item>val1</item>val2<item>val3</item></list></root>";
XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonResult = xmlMapper.readTree(xml);

      

Json result:

{"name":"john","list":{"item":"val3"}}  

      

If I enable the duplicate keys fail xmlMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY)

, an exception is thrown:
com.fasterxml.jackson.databind.JsonMappingException: Duplicate field 'item' for ObjectNode: not allowed when FAIL_ON_READING_DUP_TREE_KEY enabled

Is there a feature that fixes this problem? Is there a way to write my own deserializer that, in case of duplicate keys, will turn them into an array?

+3


source to share


1 answer


You can catch this exception and do something like:

List<MyClass> myObjects = mapper.readValue(input, new TypeReference<List<MyClass>>(){});

      



(got it from here How to use Jackson to deserialize an array of objects )

This is a hacky approach and you will need to figure out how to resume it.

-1


source







All Articles