jackson-dataformat-xml: `XmlMapper`/`UntypedObjectDeserializer` swallows duplicated elements in XML documents

Hello guys.

I think I have already seen this issue around, but, for UntypedObjectDeserializer the solution maybe a bit different.

Entity

<?xml version="1.0" encoding="UTF-8"?>
<person>
   <name>John</name>
   <parent>Jose</parent>
   <parent>Maria</parent>
   <dogs>
      <count>3</count>
      <dog>
         <name>Spike</name>
         <age>12</age>
      </dog>
      <dog>
         <name>Brutus</name>
         <age>9</age>
      </dog>
      <dog>
         <name>Bob</name>
         <age>14</age>
      </dog>
   </dogs>
</person>

Code

new XmlMapper().readValue(xml, Object.class);       

Output

{
  "name" : "John",
  "parent" : "Maria",
  "dogs" : {
    "count" : "3",
    "dog" : {
      "name" : "Bob",
      "age" : "14"
    }
  }
}

Problem

Duplicated elements in the entity get swallowed by current UntypedObjectDeserializer implementation.

I can’t use Typed Objects. In my use case, I don’t have any typed objects, because I don’t know how objects are sent to me.

Possible Solution

While creating the Map for the data, check if there are duplicated keys, and start an Array, with this approach, the output would be:

{
  "name" : "John",
  "parent" : [ "Jose", "Maria" ],
  "dogs" : {
    "count" : "3",
    "dog" : [ {
      "name" : "Spike",
      "age" : "12"
    }, {
      "name" : "Brutus",
      "age" : "9"
    }, {
      "name" : "Bob",
      "age" : "14"
    } ]
  }
}

How to Reproduce

Gist

Artifacts:

  • jackson-core
  • jackson-databind
  • jackson-dataformat-xml

Version:

  • 2.7.4

Conclusion

The gist implements the solution using an extended version of the UntypedObjectDeserializer.

If not the default behavior, what about creating a new DeserializationFeature to enable this(default or not)?

Should you guys like/aprove this solution, I can always fork the project and submit a pull request with the full solution as a feature or default behavior.

Thanks! Jp

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 7
  • Comments: 31 (11 by maintainers)

Commits related to this issue

Most upvoted comments

I ended up implementing suggestion, so that repeated elements result in automatic “upgrade” into List. This is done automatically when reading xml content.

Will be in 2.12(.0).

@cowtowncoder Is this (Handling duplicate elements natively) targeted for 3.0?

Absolute life saver!

In order to throw my 5 cents on the topic, for me it was crucial to readValue to Object.class instead of TypeReference of Map<String, Object>.

Thanks for the workaround provided!