【问题标题】:Can't Parse JSON data from URL无法解析来自 URL 的 JSON 数据
【发布时间】:2014-04-24 21:24:31
【问题描述】:

我无法让它在我的应用程序中正确显示。它告诉我它不能像这样解析 JSON。这是执行此操作的代码:

private class SearchActivity2 extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        String result = "";
        String s = "";
        InputStream isr = null;
        HttpClient httpclient = null;
        try {
            httpclient = new DefaultHttpClient();
        } catch (Exception ex) {
            //show.setText(ex.getMessage());
            System.exit(1);
        }
        HttpGet httpget = null;
        try {
            httpget = new HttpGet("http://deanclatworthy.com/imdb/?q=" + search);
            //System.out.println("http://deanclatworthy.com/imdb/?q=" + search);
        } catch (IllegalArgumentException ex) {
            //show.setText(ex.getMessage());
            System.exit(1);
        }
        HttpResponse response = null;

        try {
            response = httpclient.execute(httpget);
        } catch (IOException ex) {
            //show.setText(ex.getMessage());
            System.exit(1);
        }

        try {
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
        } catch (IOException ex) {
            //show.setText(ex.getMessage());
            System.exit(1);
        } catch (IllegalStateException ex) {
            //show.setText(ex.getMessage());
            System.exit(1);
        }

        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            isr.close();

            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error  converting result " + e.toString());
        }

        //parse json data
        try {

            JSONArray jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json = jArray.getJSONObject(i);
                s = s +
                        "Title : " + json.getString("title") + "\n" +
                        "Rating : " + json.getString("rating") + "\n";
            }

            //show.setText(s);
            return s;
        } catch (Exception e) {
            //TODO: handle exception
            Log.e("log_tag", "Error Parsing Data " + e.toString());
        }

        return s;
    }

    protected void onPostExecute(String s){
        showSearch.setText(s);
    }
}

目前,我只是尝试显示该网站的标题和评级。在这种情况下,无论用户输入什么,它都会是 http://deanclatworthy.com/imdb/?q= +。所以,http://deanclatworthy.com/imdb/?q=The+Incredible+Hulk 会起作用,或者类似的东西。

这里是 logcat 错误:04-24 14:34:56.009 11886-12595/com.android.movi​​es E/log_tag:

解析数据时出错 org.json.JSONException: 值 {“系列”:0,“imdbid”:“tt3628580”,“流派”:“动画,喜剧”,“imdburl”:“http://www.imdb.com/title/tt3628580/”,“投票”: "126","runtime":"21min","country":"n/a","stv":1,"languages":"English","title":"The 世界上最有趣的人 World","cacheExpiry":1398972896,"year":"132014","usascreens":0,"rating":"6.9","ukscreens":0} org.json.JSONObject 类型的无法转换为 JSONArray

【问题讨论】:

  • 我认为结果根本不是一个数组......也许是因为在我尝试使用 json 之前我读过它......

标签: android json


【解决方案1】:

当您可以通过这些简单的步骤完成时,为什么要经历所有这些。

第一步:建立连接并获取json。

public String loadJSON(String someURL) {

        String json = null;
        HttpClient mHttpClient = new DefaultHttpClient();
        HttpGet mHttpGet = new HttpGet(someURL);

        try {

            HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
            StatusLine statusline = mHttpResponse.getStatusLine();
            int statuscode = statusline.getStatusCode();
            if (statuscode != 200) {

                return null;

            }
            InputStream jsonStream = mHttpResponse.getEntity().getContent();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(jsonStream));

            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {

                builder.append(line);

            }

            json = builder.toString();

        } catch (IOException ex) {

            ex.printStackTrace();

            return null;
        }
        mHttpClient.getConnectionManager().shutdown();
        return json;

    }

下一步:使用该方法加载json,如下所示:

注意:您可以使用上述方法连接到任何url并获取json。

public void ParseJSON(String URL){

        try{

            JSONObject mainJSONObject = new JSONObject(loadJSON(URL));
            //If want just that particular block of information.
            /*String getTitle = mainJSONObject.getString("title");
            String Country = mainJSONObject.getString("country");*/


            for(int i = 0;i<mainJSONObject.length();i++){//If you want all the data from the json.

                String getTitle = mainJSONObject.getString("title");
                String Country = mainJSONObject.getString("country");
                //Rest you will figure it out.


            }

        }catch (Exception e){

            e.printStackTrace();

        }

    }

下一步:使用 AsyncTask 在后台加载内容。

public class someTask extends AsyncTask<Void,Void,Void>{

        ProgressDialog pDialog;
        Context context;
        String URL;

        public someTask(Context context, String someURL){

            super();
            this.context = context;
            this.URL = someURL;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);
            pDialog.setMessage("Loading files...");
            pDialog.setIndeterminate(true);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {

            ParseJSON(URL);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();
        }
    }

最后一步:只需像这样在 onCreate() 中执行任务:

new someTask(context,your_url_you_want_to_execute).execute();

希望这个解决方案很简单,可以帮助您解决问题。让我知道它有效。祝你好运..:)

【讨论】:

  • 您要对代码进行一些调整。再次强调,这只是为了解决问题。
  • 似乎可以,但我需要将解析结果设置为 TextView。
  • 在 pDialog.dismiss() 之前;只需在 onPostExecute() 中设置您的文本视图,例如: your_text_view.setText(您的 Json 值..即您获取值的字符串);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 2019-08-01
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多