2011-06-24 66 views
13

我有要求以xml-structure中的字符串或json-structure的形式返回數據庫中的結果。 我有一個解決方案,但我不知道,如果這是解決這個問題的最好方法。 我有兩種方法在這裏:spring mvc rest響應json和xml

@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結構我認爲。

我該怎麼做,該春確定一個方法應該返回一個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 

我希望有人能幫助我。

回答

8

哇......當你和Spring一起工作的時候,假設有人提出反對同樣的問題。你可以轉儲所有的服務器端JSON的產生,因爲所有你需要做的是:

  1. 包括傑克遜JSON JAR文件在您的應用程序
  2. 設置RequestMapping返回類型@ResponseBody(yourObjectType)

春天會自動將您的對象轉換爲JSON。真。像魔術一樣工作。

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

+1

沒有。它會自動奇蹟般地返回xml ... – Jan

+1

如果您將方法的返回類型設置爲「@ResponseBody MyObject」並且在您的類路徑中包含Jackson JAR,則Spring將執行轉換。你在使用Spring 3嗎? – atrain

+0

感謝上ResponseBody的信息...我要補充一點,雖然:@RequestMapping(值= 「/寵物/ {} petId」,方法= RequestMethod.GET,產生= 「應用/ JSON」) @ResponseBody public Pet getPet(@PathVariable String petId,Model model){ // implementation omitted } –

13

如果您在使用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/

+0

這是一個很好的答案,它考慮到了xml和json的有效服務。這不像Jersey的Jaxson實現那麼簡單,但我會接受它。 –

4

您可以使用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(); 
} 
0

這裏我寫的方法它將XML作爲請求的請求參數映射URL

我在這裏張貼XML到我的網址 「的BaseURL /用戶/ 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>[email protected]</userName></userEntity>" 

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

0

最簡單的方式做到這一點得到JSON的反應是: 使用Spring 3.1中,你可以做如下

  1. 在你的pom.xml文件(希望您使用的是Maven項目),增加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; 
    } 
    
1

如果有人使用Spring引導以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格式產生響應。