user2903095
user2903095

Reputation:

JSON response returning null

I am currently working on a french Android application, and the JSON response is returning null when I have an accent like (é) or (è) in it. How can I avoid this please? Can anybody help me to solve my problem please? This is my code:

public class JSONParserList
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParserList() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params)
{
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch (ClientProtocolException e) 
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    try
    {
        //BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8000);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = r.readLine()) != null)
        {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSONList", json);
    }
    catch (Exception e)
    {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Parse the string to a JSON object
    try
    {
        jObj = new JSONObject(json);
    }
    catch (JSONException e)
    {
        Log.e("JSON Parser", "Error parsing data [" + e.getMessage() + "] " + json);
    }

    // Return JSON String
    return jObj;

}
}

Please help me.

Upvotes: 0

Views: 1209

Answers (2)

Light Yagami
Light Yagami

Reputation: 11

Try changing this

httpPost.setEntity(new UrlEncodedFormEntity(params));

To

httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 

Upvotes: 0

Allan McLemore
Allan McLemore

Reputation: 1232

Since your client parser is hard-coded to expect UTF-8 encoded data, I'd double-check to server payload response and verify charset is in fact UTF-8 encoded.

  • Tools like Wireshark and Fiddler are handy for inspecting response payloads.

  • Inspect your response by going to the hex view. é should map to c3 89.

  • Also verify the charset encoding which should be:

     Content-Type   application/json; charset=utf-8
     or
     Content-Type   text/html; charset=UTF-8
    

Upvotes: 0

Related Questions