I am trying to get a (JSON formatted) string from a url and use it as a Json object. I lose UTF-8 encoding when I convert 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 receive data from the server, the following code displays the correct characters:
String output = getUrlContents(url);
Log.i("message1", output);
But when I convert the output string to JSONObject, Persian characters become question marks like this ??????. (messages is the name of the 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);
source
share