Click here to Skip to main content
Click here to Skip to main content

JSP GSON Encoding Problem

, 13 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

@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)

Share

About the Author

ROMzesFest
Software Developer (Junior)
Russian Federation Russian Federation
Software Developer

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.141015.1 | Last Updated 13 Mar 2014
Article Copyright 2014 by ROMzesFest
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid