Search code examples
jsonxmlspringvalidationmarshalling

Why Spring Boot doesn't marshall XML correctly / ignores XML javax.xml.bind.annotation.*?


Don't know why but marshaller in my Spring Boot web / REST application ignores javax.xml.bind.annotation.* annotations.

ValidationErrorResponse should be marshaled into Errors XML field.

@XmlRootElement(name = "Errors")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso(ValidationError.class)
public class ValidationErrorResponse {

    @XmlElementWrapper(name = "Errors")
    private List<ValidationError> errors = new ArrayList<ValidationError>();

    @XmlAttribute(name = "count")
    public int getCount() {
        return this.errors.size();
    }

    public void addError(ValidationError error) {
        this.errors.add(error);
    }

    @XmlElement(name = "Errors")
    public List<ValidationError> getErrors() {
        return errors;
    }
}

ValidationError should be marshaled into Error XML subfield in Errors field.

import javax.xml.bind.annotation.*;

    @XmlRootElement(name = "Error")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ValidationError {

        @XmlAttribute(name = "field")
        private final String field;

        @XmlAttribute(name = "message")
        private String message;

        public ValidationError(String field) {
            this.field = field;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getField() {
            return field;
        }

        public String getMessage() {
            return message;
        }
    }

But it returns this XML string

<ValidationErrorResponse>
    <errors>
        <errors>
            <field>transaction</field>
            <message>message...</message>
        </errors>
        <errors>
            <field>transaction</field>
            <message>message...</message>
        </errors>
        <errors>
            <field>transaction</field>
            <message>message...</message>
        </errors>
    </errors>
    <count>3</count>
</ValidationErrorResponse>

and should be

<Errors count=3>
<Error field="..." message="....">
<Error field="..." message="....">
<Error field="..." message="....">
</Errors>

What am I doing wrong?


Solution

  • The problem causes jackson-dataformat-xml dependency on my classpath:

    <dependency>
                 <groupId>com.fasterxml.jackson.dataformat</groupId>
                 <artifactId>jackson-dataformat-xml</artifactId>
                 <version>2.8.5</version>
            </dependency>
    

    when I put it off all works as expected.