将String转换为Android JSONObject会丢失utf-8 [英] Converting String to Android JSONObject loses utf-8
问题描述
我试图从URL获取(JSON格式)字符串,并将其作为Json对象使用.将String转换为JSONObject时,我丢失了UTF-8编码.
I am trying to get a (JSON formatted) String from a URL and consume it as a Json object. I lose UTF-8 encoding when I convert the String to JSONObject.
这是我用来连接到网址并获取字符串的函数:
This is The function I use to connect to the url and get the string:
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();
}
当我从服务器获取数据时,以下代码显示正确的字符:
When I get data from server, the following code displays correct characters:
String output = getUrlContents(url);
Log.i("message1", output);
但是当我将输出字符串转换为JSONObject时,波斯字符变成了像这样的问号??????. (消息是JSON中数组的名称)
But when I convert the output string to JSONObject the Persian characters becomes question marks like this ??????. (messages is the name of array in JSON)
JSONObject reader = new JSONObject(output);
String messages = new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
Log.i("message2", messages);
推荐答案
您要让Java使用ISO-8859-1将字符串(具有键message
)转换为字节,然后从这些字符串创建新的String字节,解释为UTF-8.
You're telling Java to convert the string (with key message
) to bytes using ISO-8859-1 and than to create a new String from these bytes, interpreted as UTF-8.
new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
您可以简单地使用:
String messages = reader.getString("messages");
这篇关于将String转换为Android JSONObject会丢失utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!