I' ve a Spring MVC bean and I would like to return turkish character by setting encoding UTF-8. but although my string is "şŞğĞİıçÇöÖüÜ" it returns as "??????çÇöÖüÜ". and also when I look at the response page, which is internet explorer page, encoding is western european iso, not UTF-8.
Here is the code:
    @RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public @ResponseBody String getMyList(HttpServletRequest request, HttpServletResponse response) throws CryptoException{
    String contentType= "text/html;charset=UTF-8";
    response.setContentType(contentType);
    try {
        request.setCharacterEncoding("utf-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    response.setCharacterEncoding("utf-8");     
    String str="şŞğĞİıçÇöÖüÜ";
    return str;
}   
                I've figured it out, you can add to request mapping produces = "text/plain;charset=UTF-8"
@RequestMapping(value = "/rest/create/document", produces = "text/plain;charset=UTF-8")
@ResponseBody
public void create(Document document, HttpServletRespone respone) throws UnsupportedEncodingException {
    Document newDocument = DocumentService.create(Document);
    return jsonSerializer.serialize(newDocument);
}
see this blog post for more details on the solution
in your dispatcher servlet context xml, you have to add a propertie 
"<property name="contentType" value="text/html;charset=UTF-8" />" on your viewResolver bean.
we are using freemarker for views.
it looks something like this:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
       ...
       <property name="contentType" value="text/html;charset=UTF-8" />
       ...
</bean>
                        Convert the JSON string to UTF-8 on your own.
@RequestMapping(value = "/example.json", method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {
    return "{ 'text': 'äöüß' } ".getBytes("UTF-8");
}
                        In Spring 5, or maybe in earlier versions, there is MediaType class. It has already correct line, if you want to follow DRY:
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
So I use this set of controller-related annotations:
@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
    // ... Methods here
}
It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With