Cannot parse and display non-utf8 characters read from an http request
encoding, java, json, parsing
Solution
The issue you have is most likely caused by incorrect setting of the character encoding at the point that you are reading in the http response from google. Can you post the code that actually gets URL and parses it into the JSON object?
As an example run the following:
public class Test1 {
public static void main(String [] args) throws Exception {
// just testing that the console can output the correct chars
System.out.println("\"title\":\"مطبخ مطايب - كباب الدجاج والخضار بصلصة الروب");
URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=rz+img+news+recordid+border");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
// the important bit is here..........................\/\/\/
InputStreamReader reader = new InputStreamReader(is, "utf-8");
StringWriter sw = new StringWriter();
char [] buffer = new char[1024 * 8];
int count ;
while( (count = reader.read(buffer)) != -1){
sw.write(buffer, 0, count);
}
System.out.println(sw.toString());
}
}
This is using the rather ugly standard `URL.openConnection()` that's been around since the dawn of time. If you are using something like Apache httpclient then you can do this really easily.
For a bit of back ground reading on encoding and maybe an explaination of why `new String (str.getBytes(), "UTF8");` will never work read Joel's article on unicode
Problem
I'm using Java to parse this request http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=rz+img+news+recordid+border which has as a result this (truncated for the sake of brevity) JSON file: ``` {"responseData":{"results": <...> "visibleUrl":"www.coolcook.net", "cacheUrl":"http://www.google.com/search?q\u003dcache:p4Ke5q6zpnUJ:www.coolcook.net", "title":"مطبخ مطايب - كباب الدجاج والخضار بصلصة الروب", "titleNoFormatting":"مطبخ مطايب - كباب الدجاج والخضار بصلصة الروب","\u003drz+img+news+recordid+border"}}, <...> "responseDetails": null, "responseStatus": 200} ``` My problem lies in the arabic characters returned (which could be any non-unicode for that matter). I tried to convert them back to unicode using something like: ``` JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); JSONObject j = ja.getJSONObject(i); str = j.getString("titleNoFormatting"); logger.log("before: " + str); // this is just my version of println enc_str = new String (str.getBytes(), "UTF8"); logger.log("after: " + enc_str); ``` However, both the 'before' and 'after' results are the same: a set of ????'s, regardless of whether I output them in the server log file or in an HTML page. Is there another way to get back the arabic characters and output them in a webpage? Does JSON have any supporting functionality for this sort of problem perhaps in order to read the non-utf characters straight away from the JSONObject?