Monday, 5 March 2018

How to provide XML response instead of JSON from your API ?


By default, @Entity annotation provides JSON compatibility.

In order to return XML format, you must define your entity class as a XML root element also.
Use @XmlRootElement to indicate the root element of the XML.
If your entity name is different in the XML than in the entity class, use name attribute.
@XmlRootElement(name = "emp")

@XmlAccessorType annotation is used to indicate XML fields are inside the entity class.

You can use @XmlElement annotation with the field, if the XML field name is different than in the entity class. 

EXAMPLE
@XmlRootElement
@XmlAccessorType(XMLAccessType.FIELD)@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)

    private Long id;

    @NotNull
    @Size(min = 2, max = 10)
    @Column(length=60, updatable=false)

    private String name;
    

    @XmlElement(name = "monthly_salary")
    private double salary;


    // Getters and setters
       
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
    }

 }


No comments:

Post a Comment

Note: only a member of this blog may post a comment.