Sim*_*ler 13 xml rest spring json mongodb
我要求将数据库中的结果作为xml-structure中的字符串或json-structure返回.我有一个解决方案,但我不知道,如果这是解决这个问题的最佳方法.我有两种方法:
@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);
}
Run Code Online (Sandbox Code Playgroud)
对于第一种方法,我需要一个更好的解决方案,我已经在这里问过: spring mvc rest mongo dbobject response
接下来就是,我在配置中插入了一个json转换器:
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
当我将第一个方法的内容类型更改为"application/json"时,它可以正常工作,但是xml响应不再起作用,因为json转换器想要将xml字符串转换为json-structure.
我该怎么做,那个spring识别出一个方法应该返回一个json类型而另一个方法是一个普通的xml作为字符串的区别?我用accept标志尝试了它:
@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET, headers = "Accept=application/json")
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我收到以下错误:
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.StackOverflowError
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我.
Wil*_*ler 13
如果您使用的是Spring 3.1,那么您可以利用注释produces上的新元素@RequestMapping来确保您可以根据需要生成XML或JSON,即使在同一个应用程序中也是如此.
我在这里写了一篇关于此的帖子:
哇......当你和Spring一起工作时,假设其他人遇到了同样的问题.您可以转储所有服务器端JSON生成,因为您需要做的就是:
RequestMapping返回类型设置为@ResponseBody(yourObjectType)Spring会自动将您的对象转换为JSON.真.像魔术一样工作.
Doc for @ResponseBody:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody