Search code examples
jackson-databind

Jackson XML parsing, two wrappers have the same child element


My XML is a workflow exported from Jira. It looks like this:

<workflow>
    <initial-actions>
        <action>...</action>
        <action>...</action>
    </initial-actions>
    <global-actions>
        <action>...</action>
        <action>...</action>
    </global-actions>
</workflow>

Trying to parse it into a POJO, I have Workflow class defined like this:

@JacksonXmlRootElement(localName = "workflow")
public class Workflow implements XMLDocumentHeader {

    @JacksonXmlElementWrapper(localName = "initial-actions")
    @JacksonXmlProperty(localName = "action")
    private List<Action> initialActions = new ArrayList<>();
    @JacksonXmlElementWrapper(localName = "global-actions")
    @JacksonXmlProperty(localName = "action")
    private List<Action> globalActions = new ArrayList<>();
}

But that is not allowed because I have the localName "action" associated with two setters:

java.lang.IllegalArgumentException: Conflicting setter definitions for property "action"

But if I omit @JacksonXmlProperty(localName = "action"), then when I serialize the POJO, the output will be incorrect:

<initial-actions>
    <initialActions>            
    </initialActions>
</initial-actions>
<global-actions>
    <globalActions>
    </globalActions>
</global-actions>

I have @JacksonXMLRootElement(localName = "action") for the Action class too, but it doesn't do anything.

How can I have two @JacksonXmlElementWrapper with the same @JacksonXMLProperty(localName)?


Solution

  • Problem solved by adding Actions class.

    @JacksonXmlRootElement
    public class Actions {
        @JacksonXmlElementWrapper(useWrapping = false)
        @JacksonXmlProperty(localName = "action")
        private List<Action> actions = new ArrayList<>();
    }
    

    Then use Actions instead of List<Action> in Workflow:

    @JacksonXmlProperty(localName = "initial-actions")
    private Actions initialActions;
    @JacksonXmlProperty(localName = "global-actions")
    private Actions globalActions;