安卓: [{"name":"Lata de At\u00fan natural"}]
[{"name":"Lata de At\u00fan natural"}]
而且,当我得到的名称和值设置为一个TextView文本打印它而不是Atún natural
:有特殊字符
问题描述:
我收到此JSON从API解析JSON。安卓:</p> <pre><code>[{"name":"Lata de Atu00fan natural"}] </code></pre> <p>而且,当我得到的名称和值设置为一个TextView文本打印它而不是<code>Atún natural</code>:有特殊字符
我得到并解析了像这样的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();
任何想法?
答
附录显示处理JSON数据。
\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
我试过了,我得到一个原始字符串像这样[{ “Name”: “拉塔德ATN自然”}]。也许问题出在API中?这很奇怪,因为当我与邮递员打电话时,我得到这个原始字符串与\ u00fan .... – Victor
我不这么认为。如果API本身存在问题,则无法使用邮递员获取正确的字符串。代码中可能存在一个问题,它通过Internet接受UTF-8编码的JSON响应。 – hata