我有一个返回JSON的Spring API,控制器方法使用StringBuilder
构建JSON字符串并返回JSON字符串,该字符串可以在浏览器中被视为原始JSON。
有没有更好的方法在不使用JacksonJsonView
的情况下在JSON中创建/返回结果?如果我只是将结果放在HashMap<String, String>
并返回地图那么有用吗?我尝试了但没有帮助。有什么好方法,任何人都可以建议吗?
Spring 3.0引入了@ResponseBody
注释,它可以在幕后将任意数据结构转换为JSON,而无需您的参与。只要确保杰克逊在课堂上,你就可以走了。例如:
@RequestMapping(value="/getJson", method=RequestMethod.GET)
@ResponseBody
public Map<String, Object> getJson(@RequestParam String something) {
Map<String, Object> output = new HashMap<String, Object>();
output.put("date", new Date());
output.put("input", something);
return output;
}
更多信息在spring.io blog文章中。