我想创建一个spring mvc rest调用,响应应该是mongo db(Basic)DBObject的结果。据我所知,DBObject是一个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");
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);
}
有没有人有更好的解决方案来满足这一要求?
提前很多。 西蒙答案 0 :(得分:0)
我在你的代码中看到一个奇怪的东西。你必须返回json或xml吗?如果你必须返回json,那么在你的情况下这很简单,@ ResponseBody可以做到神奇
@RequestMapping(value = "/content/json/{ids}", method = RequestMethod.GET)
@ResponseBody
public MyGreatContentObject getContentByIdsAsJSON(@PathVariable("ids") String ids) {
return this.contentService.findContentByListingId(ids);
}
无论如何,我认为你还必须多学习基础概念