標籤:
Spring MVC3返回JSON資料中文亂碼問題解決
查了下網上的一些資料,感覺比較複雜,這裡,我這幾使用兩種很簡單的辦法解決了中文亂碼問題。
Spring版本:3.2.2.RELEASE
Jackson JSON版本:2.1.3
解決思路:Controller的方法中直接通過response向網路流寫入String類型的json資料。
使用 Jackson 的 ObjectMapper 將Java對象轉換為String類型的JSON資料。
為了避免中文亂碼,需要設定字元編碼格式,例如:UTF-8、GBK 等。
代碼如下:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.fasterxml.jackson.databind.ObjectMapper; //Jsckson JSON Processerimport java.util.*;import javax.servlet.ServletOutputStream;import javax.servlet.http.*;import java.io.PrintWriter;import java.nio.charset.Charset;/** * Created with IntelliJ IDEA 12.0 * Date: 2013-03-15 * Time: 16:17 */@Controllerpublic class HomeController { @RequestMapping(value="/Home/writeJson", method=RequestMethod.GET) public void writeJson(HttpServletResponse response) { ObjectMapper mapper = new ObjectMapper(); HashMap<String,String> map = new HashMap<String,String>(); map.put("1","張三"); map.put("2","李四"); map.put("3","王五"); map.put("4", "Jackson"); String json = ""; try { json = mapper.writeValueAsString(map); System.out.println(json); //方案二 ServletOutputStream os = response.getOutputStream(); //擷取輸出資料流 os.write(json.getBytes(Charset.forName("GBK"))); //將json資料寫入流中 os.flush(); //方案一 response.setCharacterEncoding("UTF-8"); //設定編碼格式 response.setContentType("text/html"); //設定資料格式 PrintWriter out = response.getWriter(); //擷取寫入對象 out.print(json); //將json資料寫入流中 out.flush(); } catch(Exception e) { e.printStackTrace(); } //return "home"; }}
還有一種方法:設定 @RequestMapping 的 produces 參數,代碼如下所示:
思路:使用 @ResponseBody 註解直接返回json字串,為了防止中文亂碼,將@RequestMapping 的 produces 參數設定成"text/html;charset=UTF-8" 即可。
@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET, produces = "text/html;charset=UTF-8")@ResponseBodypublic Object writeJson(HttpServletResponse response){ ObjectMapper mapper = new ObjectMapper(); HashMap<String,String> map = new HashMap<String,String>(); 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;}
運行結果如所示:
Spring MVC3返回JSON資料中文亂碼問題解決(轉)