Search code examples
javaxmlspringspring-bootjackson-dataformat-xml

Spring boot XML change root element name


I wrote a spring boot application to accept a Http get Request and send a XML response as the output.I need to get following XML as output over HTTP

<response xmlns="">
    <userId>235</userId>
    <amount>345.0</amount>
</response>

And my DTO class is follows,

@XmlRootElement(name = "response")
public class CgPayment {
    @XmlElement
    private String userId;
    @XmlElement
    private double amount;

    @XmlElement
    public String getUserId() {
        return userId;
    }

    @XmlElement
    public void setUserId(String userId) {
        this.userId = userId;
    }

    @XmlElement
    public void setAmount(double amount) {
        this.amount = amount;
    }

    @XmlElement
    public double getAmount() {

        return amount;
    }
}

But i'm getting following response as the Output.

<CgPayment xmlns="">
    <userId>235</userId>
    <amount>345.0</amount>
</CgPayment>

How can I change the root element.The response type is APPLICATION_XML_VALUE


Solution

  • You can use @JacksonXmlRootElement(localName = "response") at the level of the class.

    Javadoc : http://static.javadoc.io/com.fasterxml.jackson.dataformat/jackson-dataformat-xml/2.2.0/com/fasterxml/jackson/dataformat/xml/annotation/JacksonXmlRootElement.html