Search code examples
javajackson-dataformat-xml

XmlMapper with same @XmlElement but different @XmlElementWrapper


I hava a class which has some String-Lists that I want to marshal via Jackson. And for better usage I want to have in eacht list the same Element-Name. So I annotate like this:

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;

public class MyClass
{
    public String title;

    @XmlElementWrapper(name="hints")
    @XmlElement(name="text")
    public List<String> hints;

    @XmlElementWrapper(name="warnings")
    @XmlElement(name="text")
    public List<String> warnings;

    @XmlElementWrapper(name="errors")
    @XmlElement(name="text")
    public List<String> errors;
}

But at runtime I get an exception Could not write JSON: Multiple fields representing property "text". I've also tried this with no effect:

// mapper instanceof com.fasterxml.jackson.dataformat.xml.XmlMapper
mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);

What do I need in addition?


Solution

  • Not a perfect solution, but still a good workaround when I seperate the list itself in a new class and remove wrapping (for it is wrapped by the members using this new type):

    public class StringList
    {
        @JacksonXmlElementWrapper(useWrapping = false)
        @XmlElement(name="text")
        public final List<String> list = new ArrayList<String>();
    
        public void add( String msg )
        {
            list.add( msg );
        }
    }
    

    ... so my class will look like:

    public class MyClass
    {
        public String title;
    
        public StringList hints;
    
        public StringList warnings;
    
        public StringList errors;
    }