Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode special characters from JSON (äöüß)

I develop a German App right now, it fetches the data from a JSON to a ListView. Since there are some special characters such as üöäß, with my code below, those characters are displayed as ?.

public class LooserSync extends IntentService {

    public LooserSync() {
        super("LooserSyncService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Database.OpenHelper dbhelper = new Database.OpenHelper(getBaseContext());
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        db.beginTransaction();
        HttpGet request = new HttpGet(
                "http://liebenwald.spendino.net/admanager/dev/android/projects.json");
        try {
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream instream = response.getEntity().getContent();
                BufferedReader r = new BufferedReader(new InputStreamReader(
                        instream), 8000);
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line);
                }
                instream.close();
                String bufstring = total.toString();
                JSONArray arr = new JSONArray(bufstring);
                Database.Tables tab = Database.Tables.AllTables.get(Database.Project.NAME);
                tab.DeleteAll(db);
                for (int i = 0; i < arr.length(); i++) {
                    tab.InsertJSON(db, (JSONObject) arr.get(i));
                }
                db.setTransactionSuccessful();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.endTransaction();
        db.close();

    }

}
like image 342
hectichavana Avatar asked Nov 03 '25 16:11

hectichavana


1 Answers

JSON content uses UTF-8 as default character set (see the RFC 4627, chapter 3). You have to make sure that the server returns a response with the right encoding AND to explicitly use the UTF-8 encoding for the stream reader:

BufferedReader r = new BufferedReader(new InputStreamReader(instream, "UTF-8"), 8000);
like image 192
Laurent Etiemble Avatar answered Nov 05 '25 15:11

Laurent Etiemble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!