微信發中文雙引號“”無法解析的問題

原因是發消息的時候用的是json-20160810.jar的JSONObject,裏面有一些特殊字符特殊處理的邏輯,

public static Writer quote(String string, Writer w) throws IOException {
        if (string != null && string.length() != 0) {
            char c = 0;
            int len = string.length();
            w.write(34);

            for(int i = 0; i < len; ++i) {
                char b = c;
                c = string.charAt(i);
                switch(c) {
                case '\b':
                    w.write("\\b");
                    continue;
                case '\t':
                    w.write("\\t");
                    continue;
                case '\n':
                    w.write("\\n");
                    continue;
                case '\f':
                    w.write("\\f");
                    continue;
                case '\r':
                    w.write("\\r");
                    continue;
                case '"':
                case '\\':
                    w.write(92);
                    w.write(c);
                    continue;
                case '/':
                    if (b == '<') {
                        w.write(92);
                    }

                    w.write(c);
                    continue;
                }

				// 這裏》》》特殊邏輯
                if (c >= ' ' && (c < 128 || c >= 160) && (c < 8192 || c >= 8448)) {
                    w.write(c);
                } else {
                    w.write("\\u");
                    String hhhh = Integer.toHexString(c);
                    w.write("0000", 0, 4 - hhhh.length());
                    w.write(hhhh);
                }
            }

            w.write(34);
            return w;
        } else {
            w.write("\"\"");
            return w;
        }
    }

其中雙引號的ASCII如下:
代碼:

String s = "“”";// 字符串
        char[] chars = s.toCharArray();
        System.out.println("\n\n漢字 ASCII\n----------------------");
        for (int i = 0; i < chars.length; i++) {// 輸出結果
            System.out.println(" " + chars[i] + " " + (int) chars[i]);
        }

輸出結果:

漢字 ASCII
----------------------
 “ 8220
 ” 8221

很明顯8220和8221都是走else特殊邏輯,所以在微信顯示會是\u***這種格式的。。。
以前不知所以然,總以爲微信解析不了中文字符雙引號,所以一直用英文雙引號代替。

現在如果要正確使用得改爲其他json解析包,比如Gson,這個改動有點大,有時間才行。

發佈了29 篇原創文章 · 獲贊 13 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章