我正在将同一类的 JSON 对象从 servlet 发送到小程序,但此类中的所有字符串变量都缺少一些字符,例如:'ą'、'ę'、'ś'、'ń'、'ł' . 但是,“ó”会正常显示 (?)。例如:“Zaznacz prawid ? ow ? operacj ? por ó wnywania dw ó ch zmiennych typu”
解决方案 我希望我能更彻底地解释它,但正如亨利注意到的那样,是 IDE 导致了这个问题。我使用谷歌票上的farmer1992类解决了它。它打印转义的 unicode 字符 (\u...) - 这是我的小程序正确编码字符的唯一方法。此外,我必须不时重新启动 NetBeans IDE 以强制 Tomcat servlet 正常工作(我不知道为什么 :) )。
Servlet 代码(已更新解决方案):
//begin of the servlet code extract
public void sendToApplet(HttpServletResponse response, String path) throws IOException
{
TestServlet x = new TestServlet();
x.load(path);
String json = new Gson().toJson(x);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
//out.print(json);
//out.flush();
GhettoAsciiWriter out2 = new GhettoAsciiWriter(out);
out2.write(json);
out2.flush();
}
//end of the servlet code extract
小程序代码:
//begin of the applet code extract
public void retrieveFromServlet(String path) throws MalformedURLException, IOException
{
String encoder = URLEncoder.encode(path, "UTF-8");
URL urlServlet = new URL("http://localhost:8080/ProjektServlet?action=" + encoder);
URLConnection connection = urlServlet.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String json = br.readLine();
Test y = new Gson().fromJson(json, Test.class);
inputStream.close();
}
//end of the applet code extract