spring mvc rest response json and xml

后端 未结 7 1860
無奈伤痛
無奈伤痛 2020-12-28 19:24

I have the requirement to return the result from the database either as a string in xml-structure or as json-structure. I\'ve got a solution, but I don\'t know, if this one

相关标签:
7条回答
  • 2020-12-28 19:55

    You can use ContentNegotiatingViewResolver as below:

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="defaultContentType" value="application/json" />
        <property name="ignoreAcceptHeader" value="true" />
        <property name="favorPathExtension" value="true" />
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="xml" value="application/xml" />
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <ref bean="xmlView"/>
                <ref bean="jsonView"/>
            </list>
        </property>
    </bean>
    
    <bean id="jsonView"
          class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="contentType" value="application/json;charset=UTF-8"/>
        <property name="disableCaching" value="false"/>
    </bean>
    
    <bean id="xmlView"
          class="org.springframework.web.servlet.view.xml.MarshallingView">
        <property name="contentType" value="application/xml;charset=UTF-8"/>
        <constructor-arg>
            <ref bean="xstreamMarshaller"/>
        </constructor-arg>
    </bean>
    
    
    <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
        <property name="autodetectAnnotations" value="true" />
        <property name="annotatedClass" value="demo.domain.xml.XMLResponse"/>
        <property name="supportedClasses" value="demo.domain.xml.XMLResponse"/>
    </bean>
    

    In your controller:

    @RequestMapping(value = "/get/response.json", method = RequestMethod.GET)
    public JSONResponse getJsonResponse(){
        return responseService.getJsonResponse();
    }
    @RequestMapping(value = "/get/response.xml", method = RequestMethod.GET)
    public  XMLResponse getXmlResponse(){
        return responseService.getXmlResponse();
    }
    
    0 讨论(0)
  • 2020-12-28 19:58

    Here I wrote method which take XML as request parameter from your request mapping URL

    Here I am posting XML to my URL "baseurl/user/createuser/"

        public class UserController {
        @RequestMapping(value = "createuser/" ,
        method=RequestMethod.POST,  consumes= "application/xml")
        @ResponseBody
        ResponseEntity<String> createUser(@RequestBody String requestBody ) {
    
            String r = "<ID>10</ID>"; // Put whatever response u want to return to requester
    
        return new ResponseEntity<String>(
                  "Handled application/xml request. Request body was: " 
                  + r, 
                  new HttpHeaders(), 
                  HttpStatus.OK);       
    
    
        }
    }
    

    I tested it using chrome poster where you can send any xml in content body like:

    "<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <userEntity><id>3</id><firstName>saurabh</firstName><lastName>shri</lastName><password>pass</password><userName>test@test.com</userName></userEntity>"
    

    This XML will capture by my createUser method and stored in String requestBody which i can use further

    0 讨论(0)
  • 2020-12-28 20:02

    If you are using Spring 3.1, you can take advantage of the new produces element on the @RequestMapping annotation to ensure that you produce XML or JSON as you wish, even within the same app.

    I wrote a post about this here:

    http://springinpractice.com/2012/02/22/supporting-xml-and-json-web-service-endpoints-in-spring-3-1-using-responsebody/

    0 讨论(0)
  • 2020-12-28 20:05

    If someone using Spring Boot for XML response then add the following dependency,

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

    And in the model class you are returning add the @XmlRootElement.

    @Entity
    @Table(name = "customer")
    @XmlRootElement
    public class Customer {
          //... fields and getters, setters
    }
    

    and in your controller add produces="application/xml". This will produce the response in xml format.

    0 讨论(0)
  • 2020-12-28 20:09

    Whoa...when you're working with Spring, assume someone else has come up against the same issue. You can dump all the server-side JSON generation, because all you need to do is:

    1. Include the Jackson JSON JARs in your app
    2. Set the RequestMapping return type to @ResponseBody(yourObjectType)

    Spring will auto-magically convert your object to JSON. Really. Works like magic.

    Doc for @ResponseBody: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

    0 讨论(0)
  • 2020-12-28 20:12

    Easiest way to do this to get JSON response would be: Using Spring 3.1, you could do as follows

    1. In your pom.xml file (hoping you are using a maven project), add maven dependency for jackson-mapper (http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13)

    2. Modify your code as follows and test the endpoint on postman:

      @RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
      public @ResponseBody String getContentByIdsAsJSON(@PathVariable("ids") String ids){
          String content = "";
          StringBuilder builder = new StringBuilder();
      
          List<String> list = this.contentService.findContentByListingIdAsJSON(ids);
          if (list.isEmpty()){
              content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data found</error>";
              return content;
          }
          for (String json : list){
              builder.append(json + "\n");
          }
      
          content = builder.toString();
          return content;
      }
      
    0 讨论(0)
提交回复
热议问题