Java:Gson 和编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13951640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:33:11  来源:igfitidea点击:

Java: Gson and encoding

javajsonencodinggson

提问by cdbeelala89

I am using Umlauts (?,ü,?) in a Gson that I need to pass via Http Post Body.

我在需要通过 Http Post Body 传递的 Gson 中使用变音符号 (?,ü,?)。

Unfortuenately, my web app will return null if the Umlauts are not converted somehow, and they are not.

不幸的是,如果 Umlauts 没有以某种方式转换,我的网络应用程序将返回 null,而事实并非如此。

content-type is "application/json"

内容类型是“应用程序/json”

How do I tell Gson to encode the Umlauts properly (the Umlauts are in the values, not the keys)?

我如何告诉 Gson 正确编码变音符号(变音符号在值中,而不是键中)?

回答by Wizche

I had the same problem passing umlaut to a web service in JSON. The webserver could not decode correctly those characters. By configuring the HttpClient for UTF encoding the problem disappeared, here is my working code:

我在将变音符号传递给 JSON 中的 Web 服务时遇到了同样的问题。网络服务器无法正确解码这些字符。通过为 UTF 编码配置 HttpClient 问题消失了,这是我的工作代码:

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(serverURL);
StringEntity str = null;
String jsonString = gson.toJson(yourdata);
str = new StringEntity(jsonString, HTTP.UTF_8);
request.setEntity(str);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
client.execute(request);

回答by Miguel Teixeira

You could try to set

你可以尝试设置

charset=UTF-8

to force the encoding.

强制编码。

回答by Rohit Kumar

You can encode Umlauts into decimal entities before passing to gson. from json you can decode these entities.

在传递给 gson 之前,您可以将变音符号编码为十进制实体。从 json 你可以解码这些实体。

/* encode unicode characters in a given string */
    private static String getEncodedText(String text) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            int codePoint = text.codePointAt(i);

            if (codePoint >= 0 && codePoint <= 126 
                    && (codePoint != 34 && codePoint != 39
                            && codePoint != 60 && codePoint != 62
                            && codePoint != 94 && codePoint != 96 && codePoint != '_')) {
                sb.append(ch);
                continue;
            }


            sb.append(convertToEntity(String.valueOf(codePoint)));
        }

        return sb.toString();
    }


    public static String convertToEntity(String decimalValue) {
        return "&#" + decimalValue+ ";";
    }