2013-04-16 35 views
2

我有一個Spring API返回JSON,控制器方法使用StringBuilder構建JSON字符串,並返回JSON字符串,該字符串在瀏覽器中可以被視爲原始JSON。Spring Controller JSON

有沒有更好的方式創建/返回JSON結果而不使用JacksonJsonView?如果我只是把結果放在HashMap<String, String>並返回地圖是否有效?我嘗試過但沒有幫助。有沒有什麼好的方法,有人可以建議嗎?

謝謝!

回答

3

Spring 3.0引入了@ResponseBody註釋,該註釋可將幕後任意數據結構轉換爲JSON,而無需您參與。只要確保傑克遜在班級路線上,你就可以走了。例如:在Springsource blog

+1

+1回答得好

@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; } 

更多信息。您可能還想查看Controller [**]中支持的方法返回類型** [documentation](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc) .html) –

+0

非常感謝! –