Introduction
GSON does not properly render non-English letters while converting Java object to json string.
Right from database to browser, all data is properly treated as UTF-8, but when GSON took place I saw only question marks.
I found solutions that did not work for me, so I've decided to post my solution.
Working Code Example
I'll show the entire doPost
method. It is redundant but you'll be able to see the whole picture.
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF8");
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
Object data = retrieveData();
Gson gson = new GsonBuilder().create();
gson.toJson(data, writer);
}
At first, I think that response.getWriter()
returns already UTF-8-oriented PrintWriter
. But you have to specify it explicitly via response.setCharacterEncoding("UTF8")
.
Hope this helps!