Android:使用特殊字符解析JSON

时间:2015-10-18 13:45:25

标签: android json

我从API接收此JSON:

[{"name":"Lata de At\u00fan natural"}]

并且,当我获得名称值并在TextView中设置为文本时,它会打印Atn natural而不是Atún natural

我在AsyncTask中得到并解析了这个JSON。

DataOutputStream printout;

    URL url = new URL(serverUrl+url_to);
    HttpURLConnection conn = (HttpURLConnection ) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setReadTimeout(10000); // millis
    conn.setConnectTimeout(15000); // millis
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Host", "android.schoolportal.gr");
    conn.setRequestProperty("Accept-Language", "UTF-8");
    conn.setRequestProperty("Content-type", "application/json;charset=windows-1251");
    conn.connect();

    String str = this.data.toString();
    byte[] data_post=str.getBytes("UTF-8");

    // Send POST output.
    printout = new DataOutputStream(conn.getOutputStream());
    printout.write(data_post);
    printout.flush ();
    printout.close ();

    //Get Response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 8);
    String line;
    StringBuffer response = new StringBuffer();
    while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();

    return response.toString();

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

\u00fa是一个unicode UTF-8编码字符。它不是windows-1251编码的字符。所以这一行:

conn.setRequestProperty("Content-type", "application/json;charset=windows-1251");

应该是这样的:

conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");

<小时/> 附录以显示处理JSON数据。

在下面的代码中,我只是使用url.openStream()来获取JSON数据。

new Thread(new Runnable() {
    @Override
    public void run() {
        URL url = null;
        try {
            url = new URL(JSON_RESPONSE_URL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try (InputStream inputStream = url.openStream();
             InputStreamReader inputStreamReader
                     = new InputStreamReader(inputStream, "UTF-8")
        ) {
            StringBuffer stringBuffer = new StringBuffer();
            char[] buffer = new char[BUFFER_SIZE];
            while (inputStreamReader.read(buffer, 0, BUFFER_SIZE) != -1) {
                stringBuffer.append(buffer);
            }

            String jsonRaw = stringBuffer.toString();
            Log.d("RAW_STRING", jsonRaw);

            // in the below three lines, parsing it as JSON data
            JSONArray jsonArray = new JSONArray(jsonRaw);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String jsonString = jsonObject.getString("name");
            Log.d("JSON_STRING", jsonString);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }
}).start();

结果是:

D/RAW_STRING: [{"name":"Lata de At\u00fan natural"}]
D/JSON_STRING: Lata de Atún natural