0

I have issue with encoding of Spring boot REST API special cs_CS characters.

Example:

@ResponseBody
@RequestMapping("/api/test")
public String test(){
    String specialCH = "ěščřžýáíéúů";
    System.out.println(specialCH);

    return specialCH;
}


2020-11-16 11:22:04.557  INFO 7400 --- [           main] cz.fry.chmi.ChmiApplication              : Started ChmiApplication in 5.187 seconds (JVM running for 5.703)
2020-11-16 11:22:05.167  INFO 7400 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-11-16 11:22:05.168  INFO 7400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-11-16 11:22:05.175  INFO 7400 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 7 ms
ěščřžýáíéúů

Result in browser:

result

application.properties:

server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true

OS Windows 10 1909.

PS: If I create file test.html ->

+ěššččřřžýáíéáý

Result in browser:

result

Luboš Hájek
  • 342
  • 4
  • 14
  • Your `String specialCH = "ěščřžýáíéúů";` seems to be encoded as `cp852` but interpreted as `cp850` or `cp437`? – JosefZ Nov 16 '20 at 11:08
  • I don't know but if I set `server.servlet.encoding.charset=CP852` same result. – Luboš Hájek Nov 16 '20 at 11:12
  • No, no, no! We are in 3rd millennium so switch to UTF-8 everywhere… – JosefZ Nov 16 '20 at 11:17
  • Yes, but every encoding `cp852 ISO8859-1/2 UTF-8` return `????` instead of `ěščř` – Luboš Hájek Nov 16 '20 at 11:23
  • I mean another [mojibake](https://en.wikipedia.org/wiki/Mojibake) mechanism. Here's an example in Python: `'ěščřžýáíé'.encode('cp850','replace').decode('cp850')` yields `?????ýáíé`. Sorry, I don't speak `java`… – JosefZ Nov 16 '20 at 11:36

1 Answers1

2

I found solution

Just need force UTF-8 encoding in Spring MVC returning String:

In @RequestMapping, use:

produces = MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"

Luboš Hájek
  • 342
  • 4
  • 14