我有要求以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
我希望有人能幫助我。
沒有。它會自動奇蹟般地返回xml ... – Jan
如果您將方法的返回類型設置爲「@ResponseBody MyObject」並且在您的類路徑中包含Jackson JAR,則Spring將執行轉換。你在使用Spring 3嗎? – atrain
感謝上ResponseBody的信息...我要補充一點,雖然:@RequestMapping(值= 「/寵物/ {} petId」,方法= RequestMethod.GET,產生= 「應用/ JSON」) @ResponseBody public Pet getPet(@PathVariable String petId,Model model){ // implementation omitted } –