我正在尝试从URL获取(JSON格式)字符串,并将其作为Json对象使用。将字符串转换为JSONObject时,我丢失了UTF-8编码。
这是我用来连接网址并获取字符串的函数:
private static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
return content.toString();
}
当我从服务器获取数据时,以下代码显示正确的字符:
String output = getUrlContents(url);
Log.i("message1", output);
但是,当我将输出字符串转换为JSONObject时,波斯字符变成了这样的问号??????。(消息是JSON中数组的名称)
JSONObject reader = new JSONObject(output);
String messages = new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
Log.i("message2", messages);
您要告诉Javamessage
使用ISO-8859-1将字符串(带有key )转换为字节,然后从这些字节创建一个新的String(解释为UTF-8)。
new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
您可以简单地使用:
String messages = reader.getString("messages");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句