還有一種方法:設置 @RequestMapping 的 produces 參數,代碼如下所示:
思路:使用 @ResponseBody 註解直接返回json字符串,爲了防止中文亂碼,將@RequestMapping 的 produces 參數設置成"text/html;charset=UTF-8" 即可。
@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET, produces = "text/html;charset=UTF-8")
@ResponseBody
public Object writeJson(HttpServletResponse response)
{
ObjectMapper mapper = new ObjectMapper();
HashMap map = new HashMap();
map.put("1","張三");
map.put("2","李四");
map.put("3","王五");
map.put("4", "Jackson");
String json = "";
try
{
json = mapper.writeValueAsString(map);
System.out.println(json);
}
catch(Exception e)
{
e.printStackTrace();
}
return json;
}
————————————————
版權聲明:本文爲CSDN博主「weixin_39521651」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_39521651/article/details/114355791