检索Json数组

时间:2010-04-30 07:56:16

标签: android json

我正在尝试从以下网址中检索值:http://rentopoly.com/ajax.php?query=Bo。我想让所有建议的值逐一显示在列表视图中。这就是我想要做的......

    public class AlertsAdd {
    public ArrayList<JSONObject> retrieveJSONArray(String urlString) {
        String result = queryRESTurl(urlString);
        ArrayList<JSONObject> ALERTS = new ArrayList<JSONObject>();
        if (result != null) {

            try {
                JSONObject json = new JSONObject(result);
                JSONArray alertsArray = json.getJSONArray("suggestions");
                for (int a = 0; a < alertsArray.length(); a++) {
                    JSONObject alertitem = alertsArray.getJSONObject(a);
                    ALERTS.add(alertitem);
                }
                return ALERTS;
            } catch (JSONException e) {
                Log.e("JSON", "There was an error parsing the JSON", e);                
            }           
        }
        JSONObject myObject = new JSONObject();
        try {
            myObject.put("suggestions",myObject.getJSONArray("suggestions"));
            ALERTS.add(myObject);
        } catch (JSONException e1) {
            Log.e("JSON", "There was an error creating the JSONObject", e1);
        }
        return ALERTS;
    }
    private String queryRESTurl(String url) {
        // URLConnection connection;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response;
        try {           
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
        if (entity != null) {
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);
                instream.close();
                return result;
            }
        } catch (ClientProtocolException e) {
            Log.e("REST", "There was a protocol based error", e);
        } catch (IOException e) {
            Log.e("REST", "There was an IO Stream related error", e);           
        }
        return null;
    }

    /**
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

这是适配器代码......

    public class AlertsAdapter extends ArrayAdapter<JSONObject> {
    public AlertsAdapter(Activity activity, List<JSONObject> alerts) {
        super(activity, 0, alerts);
    }
     @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Activity activity = (Activity) getContext();
            LayoutInflater inflater = activity.getLayoutInflater();
            View rowView = inflater.inflate(R.layout.list_text, null);
            JSONObject imageAndText = getItem(position);
            TextView textView = (TextView) rowView.findViewById(R.id.last_build_stat);
            try {
                textView.setText((String)imageAndText.get("suggestions"));
            } catch (JSONException e) {
                textView.setText("JSON Exception");
            }
            return rowView;
        }
}

这是logcat ......

    04-30 13:09:46.656: INFO/ActivityManager(584): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.WorldToyota/.Alerts }
04-30 13:09:50.417: ERROR/JSON(924): There was an error parsing the JSON
04-30 13:09:50.417: ERROR/JSON(924): org.json.JSONException: JSONArray[0] is not a JSONObject.
04-30 13:09:50.417: ERROR/JSON(924):     at org.json.JSONArray.getJSONObject(JSONArray.java:268)
04-30 13:09:50.417: ERROR/JSON(924):     at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:30)
04-30 13:09:50.417: ERROR/JSON(924):     at com.WorldToyota.Alerts.onCreate(Alerts.java:20)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-30 13:09:50.417: ERROR/JSON(924):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 13:09:50.417: ERROR/JSON(924):     at android.os.Looper.loop(Looper.java:123)
04-30 13:09:50.417: ERROR/JSON(924):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-30 13:09:50.417: ERROR/JSON(924):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 13:09:50.417: ERROR/JSON(924):     at java.lang.reflect.Method.invoke(Method.java:521)
04-30 13:09:50.417: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-30 13:09:50.417: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-30 13:09:50.417: ERROR/JSON(924):     at dalvik.system.NativeStart.main(Native Method)
04-30 13:09:50.688: ERROR/JSON(924): There was an error creating the JSONObject
04-30 13:09:50.688: ERROR/JSON(924): org.json.JSONException: JSONObject["suggestions"] not found.
04-30 13:09:50.688: ERROR/JSON(924):     at org.json.JSONObject.get(JSONObject.java:287)
04-30 13:09:50.688: ERROR/JSON(924):     at org.json.JSONObject.getJSONArray(JSONObject.java:362)
04-30 13:09:50.688: ERROR/JSON(924):     at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:41)
04-30 13:09:50.688: ERROR/JSON(924):     at com.WorldToyota.Alerts.onCreate(Alerts.java:20)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-30 13:09:50.688: ERROR/JSON(924):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 13:09:50.688: ERROR/JSON(924):     at android.os.Looper.loop(Looper.java:123)
04-30 13:09:50.688: ERROR/JSON(924):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-30 13:09:50.688: ERROR/JSON(924):     at java.lang.reflect.Method.invokeNative(Native Method)
04-30 13:09:50.688: ERROR/JSON(924):     at java.lang.reflect.Method.invoke(Method.java:521)
04-30 13:09:50.688: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-30 13:09:50.688: ERROR/JSON(924):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-30 13:09:50.688: ERROR/JSON(924):     at dalvik.system.NativeStart.main(Native Method)

Plz帮助我解析这个脚本并以列表格式显示值....

4 个答案:

答案 0 :(得分:4)

查看此示例 - 使用您尝试访问的相同服务,并且也基于Android。

http://damonsk.com/2010/01/jsonarray-httpclient-android/

答案 1 :(得分:1)

您需要首先从您获得的字符串中获取JSONArray。然后访问特定对象。以下是可用于获取建议数组的代码:

String result = queryRESTurl(urlString);
JSONArray array =  new JSONArray( result );

JSONObject object = array.getJSONObject( 0 ); JSONArray alertsArray = object.getJSONArray( "suggestions" );

答案 2 :(得分:0)

查看JSON对象:

{
"query": "Bo",
"suggestions": ["Bognor Regis", "Bolton",  ... ]
}

我认为建议[0]不是JSONObject("an unordered collection of name/value pairs"),因此错误。它是一个普通的字符串。试试:

String alertitem = alertsArray.getString(a);

答案 3 :(得分:0)

        public static ArrayList<Sport_Teamdetail_dto> getSport_TeamDetail(String id) {

            ArrayList<Sport_Teamdetail_dto> fetchSport_TeamDetail = new ArrayList<Sport_Teamdetail_dto>();
            String result = "";
            InputStream is = null;

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id", id));


            try {
                // http post
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url + "fetch_allsportdata.php?");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

               // http Get
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
                is = httpResponse.getEntity().getContent();


            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            // parse json data
            try {
                JSONObject json_obj = new JSONObject(result);
                JSONArray j_Arr_sco_id = json_obj.getJSONArray("scid");
                JSONArray j_Arr_tn = json_obj.getJSONArray("Teamname");
                JSONArray j_Arr_vn = json_obj.getJSONArray("Venuename");
                JSONArray j_Arr_cenr = json_obj.getJSONArray("Centerreference");
                JSONArray j_Arr_ref1 = json_obj.getJSONArray("Referee1");
                JSONArray j_Arr_ref2 = json_obj.getJSONArray("Referee2");

                for (int i = 0; i < j_Arr_tn.length(); i++) {
                    Sport_Teamdetail_dto sportteamdto = new Sport_Teamdetail_dto();
                    sportteamdto.sport_scocer_id = j_Arr_sco_id.getString(i);
                    sportteamdto.sports_team_teamname = j_Arr_tn.getString(i);
                    sportteamdto.sports_venue_name_all = j_Arr_vn.getString(i);
                    sportteamdto.sports_centerreff_name_teamnm = j_Arr_cenr
                            .getDouble(i);
                    sportteamdto.sports_ref1_name_team_nm = j_Arr_ref1.getDouble(i);
                    sportteamdto.sports_ref2_name_teamnm = j_Arr_ref2.getDouble(i);

                    fetchSport_TeamDetail.add(sportteamdto);

                }

            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
            return fetchSport_TeamDetail;

        }


   public class ItemListAdapterFindStore extends ArrayAdapter<ComanWord> {
        Context context1;
        private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

        /**
         * Constructor from a list of items
         */
        public ItemListAdapterFindStore(Context context, ArrayList<ComanWord> items) {
            super(context, 0, items);
            li = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            context1 = context;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // The item we want to get the view for
            // --
            final ComanWord item = getItem(position);

            // Re-use the view if possible
            // --
            final ViewHolder holder;
            if (convertView == null) {
                convertView = li.inflate(R.layout.list_item_card, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.holder, holder);
            } else {
                holder = (ViewHolder) convertView.getTag(R.id.holder);
            }

            holder.m_text1.setText(item.getEnglish());
            holder.m_text2.setText(item.getHindi());

            if (item.getGujarati() != null && item.getGujarati() != "") {
                holder.m_text3.setText(item.getGujarati());
            }


            if(item.getFavflag() ==0){
                holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_off_holo_light);
            }else{
                holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_on_holo_light);
            }

            RelativeLayout rel = (RelativeLayout) convertView
                    .findViewById(R.id.rel_box);
            // rel.setBackgroundColor(v.getResources().getColor(R.color.bacground));
            if (mSelection.get(position) != null) {

                rel.setBackgroundColor(convertView.getResources().getColor(
                        R.color.actionbarcolor1));// this is a selected position so
                                                    // make it red
            } else {
                rel.setBackgroundColor(convertView.getResources().getColor(
                        R.color.white));
            }

            holder.img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.i("fb", "AMIT::" + item.getEnglish().toString());
                    PlanetFragment.speakOut(item.getEnglish().toString());
                }
            });

            holder.img_audio1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    if(item.getFavflag() ==0){
                        holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_on_holo_light);
                    }else{
                        holder.img_audio1.setImageResource(R.drawable.apptheme_rate_star_small_off_holo_light);
                    }
                    PlanetFragment.test(position);



                }
            });

            return convertView;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        private LayoutInflater li;

        private static class ViewHolder {
            public ViewHolder(View m_rootView) {
                m_text1 = (TextView) m_rootView.findViewById(R.id.text1);
                m_text2 = (TextView) m_rootView.findViewById(R.id.text2);
                m_text3 = (TextView) m_rootView.findViewById(R.id.text3);
                img = (ImageView) m_rootView.findViewById(R.id.img_audio);

                img_audio1 = (ImageView) m_rootView.findViewById(R.id.img_audio1);
                m_text2.setTypeface(MainActivity.fonth);
                m_text3.setTypeface(MainActivity.fontg);
            }

            private TextView m_text1;
            private TextView m_text2;
            private TextView m_text3;
            private ImageView img, img_audio1;

        }

        public void setNewSelection(int position, boolean value) {
            mSelection.put(position, value);
            notifyDataSetChanged();
        }

        public boolean isPositionChecked(int position) {
            Boolean result = mSelection.get(position);
            return result == null ? false : result;
        }

        public Set<Integer> getCurrentCheckedPosition() {
            return mSelection.keySet();
        }

        public void removeSelection(int position) {
            CommonWordApp.words = "";
            mSelection.remove(position);
            notifyDataSetChanged();
        }

        public void clearSelection() {
            CommonWordApp.words = "";
            mSelection = new HashMap<Integer, Boolean>();
            notifyDataSetChanged();
        }
    }