查了下網上的一些資料,感覺比較復雜,這里,我這幾使用兩種很簡單的辦法解決了中文亂碼問題。
Spring版本:3.2.2.RELEASE
Jackson JSON版本:2.1.3
解決思路:Controller的方法中直接通過response向網絡流寫入String類型的json數據。
使用 Jackson 的 ObjectMapper 將Java對象轉換為String類型的JSON數據。
為了避免中文亂碼,需要設置字符編碼格式,例如:UTF-8、GBK 等。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
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 Processer import 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 */ @Controller public 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" 即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
@RequestMapping (value= "/Home/writeJson" , method=RequestMethod.GET, produces = "text/html;charset=UTF-8" ) @ResponseBody public 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; } |
運行結果如下圖所示:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/CBDoctor/p/4459750.html