将HttpServletRequest转换为JSON为“UTF-8”

时间:2015-09-30 11:20:09

标签: java json spring utf-8

我有方法,将HttpServletRequest转换为JSON格式:

public JsonObject requestToJson(HttpServletRequest request){

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { /*report an error*/ }

        return new JsonParser().parse(jb.toString()).getAsJsonObject();
    }

问题是,如何将请求转换为“UTF-8”编码?

更新:我检查过,默认情况下,读者将请求作为“ISO-8859-1”。如何将参数设置为阅读器,将其作为“UTF-8”。

2 个答案:

答案 0 :(得分:1)

我自己找到了解决方案。我刚刚加入到顶部:

request.setCharacterEncoding("UTF-8");

答案 1 :(得分:0)

尝试use request.setCharacterEncoding( "UTF-8"),但此方法并不适用于GET参数。

另一种方法是手动转换为UTF-8:

BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
    jb.append(new String(line.getBytes(), "UTF-8"));