spring mvc 休息响应json和xml

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6467119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:54:20  来源:igfitidea点击:

spring mvc rest response json and xml

xmljsonspringrestmongodb

提问by Simon Hofstadler

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 is the best way to solve this. I have two methods here:

我需要以 xml 结构中的字符串或 json 结构中的字符串形式从数据库返回结果。我有一个解决方案,但我不知道,这是否是解决此问题的最佳方法。我这里有两种方法:

@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
public ResponseEntity<String> getContentByIdsAsJSON(@PathVariable("ids") String ids)
{
  String content = null;
  StringBuilder builder = new StringBuilder();
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.add("Content-Type", "text/html; charset=utf-8");
  // responseHeaders.add("Content-Type", "application/json; charset=utf-8");

  List<String> list = this.contentService.findContentByListingIdAsJSON(ids);
  if (list.isEmpty())
  {
     content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data  found</error>";
     return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
  }
  for (String json : list)
  {
     builder.append(json + "\n");
  }
  content = builder.toString();
  return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}

@RequestMapping(value = "/content/{ids}", method = RequestMethod.GET)
public ResponseEntity<String> getContentByIdsAsXML(@PathVariable("ids") String ids)
{
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.add("Content-Type", "application/xml; charset=utf-8");

  String content = this.contentService.findContentByListingIdAsXML(ids);
  if (content == null)
  {
     content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error>no data found</error>";
     return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
  }
  return new ResponseEntity<String>(content, responseHeaders, HttpStatus.CREATED);
}

for the first method I need a better solution, which I already asked here: spring mvc rest mongo dbobject response

对于第一种方法,我需要一个更好的解决方案,我已经在这里问过了: spring mvc rest mongo dbobject response

The next thing is, that I inserted in the configuration a json converter:

接下来是,我在配置中插入了一个 json 转换器:

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter">
   <property name="supportedMediaTypes" value="application/json"/>
</bean>

when I change the content-type at the first method to "application/json", it works, but then the xml response doesn't work anymore, because the json converter wants to convert the xml string to json-structure I think.

当我将第一种方法中的内容类型更改为“application/json”时,它可以工作,但是 xml 响应不再起作用,因为 json 转换器想要将 xml 字符串转换为我认为的 json 结构。

what can I do, that spring identifies the difference that the one method should return a json type and the other one a normal xml as string? I tried it with the accept flag:

我能做什么,那个 spring 确定了一个方法应该返回一个 json 类型而另一个方法应该返回一个普通的 xml 作为字符串的区别?我用接受标志尝试过:

@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET, headers = "Accept=application/json")

but this doesn't work. I get the following error:

但这不起作用。我收到以下错误:

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError

I hope that somebody can help me out.

我希望有人可以帮助我。

回答by

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

如果您使用的是 Spring 3.1,您可以利用注释produces上的新元素@RequestMapping来确保您根据需要生成 XML 或 JSON,即使在同一个应用程序中也是如此。

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/

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

回答by atrain

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:

哇...当您使用 Spring 时,假设其他人遇到了同样的问题。您可以转储所有服务器端 JSON 生成,因为您需要做的就是:

  1. Include the Hymanson JSON JARs in your app
  2. Set the RequestMappingreturn type to @ResponseBody(yourObjectType)
  1. 在您的应用程序中包含 Hymanson JSON JAR
  2. RequestMapping返回类型设置为@ResponseBody(yourObjectType)

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

Spring 会自动神奇地将您的对象转换为 JSON。真的。像魔术一样工作。

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

文档@ResponseBodyhttp: //static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

回答by Mark

You can use ContentNegotiatingViewResolver as below:

您可以使用 ContentNegotiatingViewResolver 如下:

<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.MappingHymansonJsonView">
    <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();
}

回答by Lucky

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

如果有人使用 Spring Boot 进行 XML 响应,则添加以下依赖项,

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

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

在您返回的模型类中添加@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.

并在您的控制器中添加produces="application/xml". 这将产生 xml 格式的响应。

回答by Saurabh

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

在这里,我编写了将 XML 作为请求映射 URL 中的请求参数的方法

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

在这里,我将 XML 发布到我的 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:

我使用 chrome 海报对其进行了测试,您可以在其中发送内容正文中的任何 xml,例如:

"<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <userEntity><id>3</id><firstName>saurabh</firstName><lastName>shri</lastName><password>pass</password><userName>[email protected]</userName></userEntity>"

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

此 XML 将通过我的 createUser 方法捕获并存储在字符串 requestBody 中,我可以进一步使用

回答by Jobin Thomas

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

获得 JSON 响应的最简单方法是:使用 Spring 3.1,您可以执行以下操作

  1. In your pom.xml file (hoping you are using a maven project), add maven dependency for Hymanson-mapper (http://mvnrepository.com/artifact/org.codehaus.Hymanson/Hymanson-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;
    }
    
  1. 在您的 pom.xml 文件中(希望您使用的是 maven 项目),为 Hymanson-mapper 添加 maven 依赖项(http://mvnrepository.com/artifact/org.codehaus.Hymanson/Hymanson-mapper-asl/1.9.13

  2. 如下修改您的代码并在邮递员上测试端点:

    @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;
    }