轉自:http://zzqrj.iteye.com/blog/805832
前段時間,人人站內信改版,本來能正常顯示的發信人名字,現在返回一個json串,需要解析json串以正常顯示。發信人的名字以unicode編碼方式存在json串中,要想正常顯示發信人的名字,需要進行unicode到漢字的轉換操作。
本身java 是支持unicode 編碼的,所以像 str = "\u4e2d\u56fd"; 打印出來是正常的。這裏要是對 str = "\\u4e2d\\u56fd"; 這種形式的unicode碼進行的轉換。
漢字轉 unicode 可以用 Integer.toHexString(ch)。
unicode 轉漢字關鍵的是 (char)Integer.parseInt("4e2d", 16)。
- public static void testUDecode() {
- //將漢字轉換爲十六進制Unicode表示
- for (char ch : "中國".toCharArray()) {
- if (ch > 128) {
- System.out.print("\\u" + Integer.toHexString(ch));
- } else {
- System.out.print(ch);
- }
- }
- String str = "\u4e2d\u56fd\u5b66";
- System.out.println("\n"+str);//直接打印出漢字
- str = "\\u5b66\\u56fd\\u5b66";
- System.out.println(str);// 打印結果爲\u5b66\u56fd\u5b66
- //將Unicode字符串轉換爲漢字輸出
- String s[]=str.split("\\\\u");
- String t="";
- for(int j=1;j<s.length;j++){
- int ab=Integer.valueOf(s[j],16);//先將16進制轉換爲整數
- char ac=(char)ab;//再將整數轉換爲字符
- System.out.println(ac);
- t=t+ac;
- }
- System.out.println("t:"+t);
- char a=20320;
- int b=(int)a;
- System.out.println(a+","+b);
- }
- 輸出結果爲:
- \u4e2d\u56fd
- 中國學
- \u5b66\u56fd\u5b66
- 學
- 國
- 學
- t:學國學
- 你,20320