Click here to Skip to main content
15,880,543 members
Articles / JSP
Tip/Trick

JSP GSON Encoding Problem

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
13 Mar 2014CPOL 23.5K   1  
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)


Written By
Software Developer (Junior)
Russian Federation Russian Federation
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
-- There are no messages in this forum --