JSON响应返回null

时间:2013-11-24 12:32:11

标签: android json encoding

我目前正在开发一个法语Android应用程序,当我有一个像(é)或(è)这样的重音时,JSON响应返回null。我怎么能避免这个呢?有人可以帮我解决我的问题吗?这是我的代码:

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;

}
}

请帮帮我。

2 个答案:

答案 0 :(得分:0)

由于您的客户端解析器是硬编码的,以期望UTF-8编码数据,因此我会仔细检查服务器有效负载响应并验证charset实际上是UTF-8编码的。

  • WiresharkFiddler等工具可以方便地检查响应有效负载。

  • 转到十六进制视图检查您的回复。 é应该映射到 c3 89

  • 还要验证charset编码应该是:

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

答案 1 :(得分:0)

尝试更改此

httpPost.setEntity(new UrlEncodedFormEntity(params));

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