Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / JSP

JSP GSON Encoding Problem

0.00/5 (No votes)
13 Mar 2014CPOL 24.1K  
GSON does not properly render non-English letters while converting Java object to json string in JSP.

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.

Java
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setCharacterEncoding("UTF8"); // this line solves the problem
    response.setContentType("application/json");

    PrintWriter writer = response.getWriter();

    Object data = retrieveData();

    Gson gson = new GsonBuilder().create();
    gson.toJson(data, writer); // places json string right into the response
} 

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)