【问题标题】:Trouble with UTF-8 JSON file used in androidandroid中使用的UTF-8 JSON文件有问题
【发布时间】:2016-04-19 09:17:02
【问题描述】:

我正在开发一个 android 项目,我使用 JSON 与服务器交换数据。当我使用 UTF-8 格式的 JSON 文件时,问题就在这里,发生了一些崩溃并且应用程序停止了。当我不这样做时t,它工作正常。 我真的需要让我的文件采用 UTF-8 格式才能拥有正确的字符。 我在哪里失踪?提前谢谢你。

这是我的服务处理程序类:

公共类 ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

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

    return response;

}

这是我在主要活动中使用的方法:

私有类 GetContacts 扩展 AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(SecondActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(jsonStr);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // Getting JSON Array node
                if (jsonObj != null) {
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                }


                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String title = c.getString(TAG_Title);
                    String content = c.getString(TAG_CONTENT);
                    String date = c.getString(TAG_DATE);



                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, id);
                    contact.put(TAG_Title, title);
                    contact.put(TAG_CONTENT, content);
                    contact.put(TAG_DATE, date);

                    // adding contact to contact list
                    conatctlist.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        ListView lv = (ListView)findViewById(R.id.listView);
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                SecondActivity.this, contactlist,
                R.layout.list_item_2, new String[] { TAG_Title, TAG_CONTENT,
                TAG_DATE }, new int[] { R.id.name,
                R.id.email, R.id.date });

        lv.setAdapter(adapter);

    }
}//end getContacts

【问题讨论】:

  • 发生了一些崩溃,应用程序停止 - 发布堆栈跟踪,真的很难猜出哪里出了问题。

标签: android json utf-8


【解决方案1】:

可能,你必须像这样定义 HttpClient...(未测试)

HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 2015-05-24
    • 2011-01-11
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多