Accepting / returning XML/JSON request and response - Spring MVC

前端 未结 5 797
無奈伤痛
無奈伤痛 2021-01-31 04:54

I need to write a rest service which accepts XML/JSON as a input (POST method) and XML/JSON as a output (based on the input format). I have tried a below approach to achieve thi

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 05:57

    If the resource define as below

    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Student getStudent(@PathParam("id") String  id) {
     return student(); // logic to retunrs student object
    }
    

    Then the request should contains 'accept' header ('application/json' or application/xml'),
    then it returns response in json or xml format.

    Sample request :

    curl -k -X GET -H "accept: application/json" "https://172.17.0.5:8243/service/1.0/222"
    

    Sample Student class

    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    
    @XmlRootElement(name = "student")
    public class Student {
        private int id;
        private String name;
        private String collegeName;
        private int age;
        @XmlAttribute
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        @XmlElement
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        @XmlElement
        public String getCollegeName() {
            return collegeName;
        }
    
        public void setCollegeName(String collegeName) {
            this.collegeName = collegeName;
        }
    
        public int getAge() {
            return age;
        }
        @XmlElement
        public void setAge(int age) {
            this.age = age;
        }
    
    }
    

提交回复
热议问题