【发布时间】:2016-04-13 18:01:24
【问题描述】:
我正在尝试从 URL 获取(JSON 格式)字符串并将其作为 Json 对象使用。当我将字符串转换为 JSONObject 时,我丢失了 UTF-8 编码。
这是我用来连接url并获取字符串的函数:
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 时,波斯字符变成了这样的问号??????。 (messages 是 JSON 中的数组名)
JSONObject reader = new JSONObject(output);
String messages = new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
Log.i("message2", messages);
【问题讨论】:
标签: android json utf-8 jsonobject