簡體   English   中英

spring mvc 休息響應json和xml

[英]spring mvc rest response json and xml

我需要以 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);
}

對於第一種方法,我需要一個更好的解決方案,我已經在這里問過了: spring mvc rest mongo dbobject response

接下來是,我在配置中插入了一個 json 轉換器:

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

當我將第一種方法中的內容類型更改為“application/json”時,它可以工作,但是 xml 響應不再起作用,因為 json 轉換器想要將 xml 字符串轉換為我認為的 json 結構。

我能做什么,那個 spring 確定了一個方法應該返回一個 json 類型而另一個方法應該返回一個普通的 xml 作為字符串的區別? 我用接受標志嘗試過:

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

但這不起作用。 我收到以下錯誤:

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

我希望有人可以幫助我。

如果您使用的是 Spring 3.1,您可以利用@RequestMapping注釋上的新produces元素來確保您根據需要生成 XML 或 JSON,即使在同一個應用程序中也是如此。

我在這里寫了一篇關於這個的帖子:

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

哇...當您使用 Spring 時,假設其他人遇到了同樣的問題。 您可以轉儲所有服務器端 JSON 生成,因為您需要做的就是:

  1. 在您的應用程序中包含 Jackson JSON JAR
  2. RequestMapping返回類型設置為@ResponseBody(yourObjectType)

Spring 會自動神奇地將您的對象轉換為 JSON。 真的。 像魔術一樣工作。

@ResponseBody文檔: http : @ResponseBody

您可以使用 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.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>

在您的控制器中:

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

如果有人使用 Spring Boot 進行 XML 響應,則添加以下依賴項,

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

在您返回的模型類中添加@XmlRootElement

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

並在您的控制器中添加produces="application/xml" 這將產生 xml 格式的響應。

在這里,我編寫了將 XML 作為請求映射 URL 中的請求參數的方法

在這里,我將 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);       


    }
}

我使用 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>test@test.com</userName></userEntity>"

此 XML 將通過我的 createUser 方法捕獲並存儲在字符串 requestBody 中,我可以進一步使用

獲得 JSON 響應的最簡單方法是:使用 Spring 3.1,您可以執行以下操作

  1. 在您的 pom.xml 文件中(希望您使用的是 maven 項目),為 jackson-mapper 添加 maven 依賴項( http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-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; }

經過大量研究,我認為我對此有一個很好的解決方案:非常簡單,默認情況下是 spring,使用 Jackson 來處理 Json,該庫來自spring-boot-starter-web ,但 Jackson 的 Xml 擴展沒有默認情況下,您需要做的就是在您的 build.gradle 或 pom.xml 中導入jackson-dataformat-xml依賴項,現在您可以在 json 或 xml 之間切換,例如使用如下代碼:

@PostMapping(value = "/personjson")
public ResponseEntity<?> getJsonPerson (@RequestBody Person person) {
    return ResponseEntity.accepted().contentType(MediaType.APPLICATION_JSON)
    .body(person);
}

@PostMapping(value = "/personxml")
public ResponseEntity<?> getXmlPerson (@RequestBody Person person) {
    return ResponseEntity.accepted().contentType(MediaType.APPLICATION_XML)
    .body(person);
}

當人是一個bean(僅限於有@Component標簽),鎖在這兩個代碼相同的僅是的MediaType不同,它的作品!,是不是太nesesary添加“生產”和“消耗” atributes到Mapping標簽,因為默認情況下 Spring 可以同時使用 Json 和 Xml,我做了一個發送 Json 和獲取的示例。 xml,並發送 xml 獲取 Json,只需要在執行請求時在郵遞員或 curl 中指定要發送的主體的正確標頭,即 application/json 或 application/xml。

注意:這只是一種方法,JAXB 和 XmlRootElement 是另一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM