在Java中将ANSI转换为UTF-8

converting ANSI to UTF-8 in Java

本文关键字:UTF-8 转换 ANSI Java 中将      更新时间:2023-09-26

我有一个JSON格式的字符串。有像'u0025这样的字符,我需要将它们转换为它们所指的实际字符。

在Java中是否有任何直接的方法可以将这些字符转换为实际字符?

myString.convertToUTF-8();

我正在调用图形API,我得到JSON格式的响应。我想使用JSON解析器或JavaScript解析器来解析JSON并获取值。这就是我需要的。

我使用谷歌浏览器的控制台,当我分配响应到一个变量。它给了我一个错误告诉Uncaught SyntaxError: Unexpected identifier(…)

在JavScript我想使用JSON.parse(jsonString)。但是事实上我不能把这个值赋给jsonString

对于在Java中转换这些字符,我已经尝试了以下行,根本不改变字符串!

String responseFromFB = http.sendRequest(url);
byte[] b = responseFromFB.getBytes();
String str= new String(b, "UTF-8");

,这里是sendRequest()函数,我有!

private String httpReq(String URL, String QueryString) throws Exception 
{
    String url = URL;
    String urlParameters = QueryString;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept-Charset", "UTF-8");
    con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
    }
    in.close();
    return response.toString();
}

我只需要写

JSONObject jsonResponse = new JSONObject(responseFromFB);
String decodedResponseFromFB = jsonResponse.toString();