【发布时间】:2011-09-21 23:11:55
【问题描述】:
我需要将数据库中的结果作为 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>
当我将第一种方法的内容类型更改为“应用程序/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
希望有人能帮帮我。
【问题讨论】:
标签: xml json spring rest mongodb