Skip to content

XmlMapper/UntypedObjectDeserializer swallows duplicated elements in XML documents #205

@joaovarandas

Description

@joaovarandas

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions