-2

如何以 JSON 格式解析此 URL?

https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=&rsz=8 "

public class MainActivity extends ListActivity {
    private Context context;
    private static String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=pixelloid&rsz=8";

    private static final String TAG_VTYPE = "responseData";
    private static final String TAG_VCOLOR = "results";
    private static final String TAG_FUEL = "GsearchResultClass";
    private static final String TAG_TREAD = "url";
    private static final String TAG_OPERATOR = "url";
    private static final String TAG_NAME = "name";
    private static final String TAG_POINTS = "experiencePoints";

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

    ListView lv ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ProgressTask(MainActivity.this).execute();
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;

        private ListActivity activity;

        // private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }

        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                    R.layout.list_item, new String[] { TAG_VTYPE, TAG_VCOLOR,
                            TAG_FUEL, TAG_TREAD }, new int[] {
                            R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
                            R.id.treadType });

            setListAdapter(adapter);

            // selecting single ListView item
             lv = getListView();






        }

        protected Boolean doInBackground(final String... args) {

            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONArray json = jParser.getJSONFromUrl(url);

            if (json == null) {
                   // notify user
                Log.e("==>", "Failed to download file");

            } 
             else {
            for (int i = 0; i < json.length(); i++) {

                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtype = c.getString(TAG_VTYPE);

                    String vcolor = c.getString(TAG_VCOLOR);
                    String vfuel = c.getString(TAG_FUEL);
                    String vtread = c.getString(TAG_TREAD);

                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_VTYPE, vtype);
                    map.put(TAG_VCOLOR, vcolor);
                    map.put(TAG_FUEL, vfuel);
                    map.put(TAG_TREAD, vtread);
                    jsonlist.add(map);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.e("==>", "iyogbr;g;ui");

                }
            }
             }

            return null;
        }

    }

}

我正在解析这些数据:

{"responseData":{"results":[{"content":"<b>Pixelloid<\/b> Studios Visual Effects, 3D Animation Production and Training Institute.","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid - Visual Effects, 3D Animation - Production and Training","title":"<b>Pixelloid<\/b> - Visual Effects, 3D Animation - Production and Training","cacheUrl":"http:\/\/www.google.com\/search?q=cache:Uq3_USWdbwIJ:www.pixelloid.com","unescapedUrl":"http:\/\/www.pixelloid.com\/","url":"http:\/\/www.pixelloid.com\/","visibleUrl":"www.pixelloid.com"},{"content":"Pixelloid Studios Visual Effects, 3D   Animation Production and Training <b>...<\/b>","GsearchResultClass":"GwebSearch","titleNoFormatting":"Production and Training Institute - Pixelloid","title":"Production and Training Institute - <b>Pixelloid<\/b>","cacheUrl":"http:\/\/www.google.com\/search?q=cache:Pce2UIgSVDoJ:www.pixelloid.com","unescapedUrl":"http:\/\/www.pixelloid.com\/training\/","url":"http:\/\/www.pixelloid.com\/training\/","visibleUrl":"www.pixelloid.com"},{"content":"<b>Pixelloid<\/b> is an award winning 3D Animation &amp; Visual Effects Production and   Training Studio based in Hyderabad with branches in Bangalore, Visakhapatnam   <b>...<\/b>","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid Studios - YouTube","title":"<b>Pixelloid<\/b> Studios - YouTube","cacheUrl":"http:\/\/www.google.com\/search?q=cache:wrfWBrpn45AJ:www.youtube.com","unescapedUrl":"http:\/\/www.youtube.com\/user\/pixelloid","url":"http:\/\/www.youtube.com\/user\/pixelloid","visibleUrl":"www.youtube.com"},{"content":"<b>Pixelloid<\/b>, Hyderabad, India. 5896 likes · 60 talking about this · 408 were here. We   help people tell their stories effectively. We do animation, visual effects for <b>...<\/b>","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid - Hyderabad, India - Media\/News\/Publishing | Facebook","title":"<b>Pixelloid<\/b> - Hyderabad, India - Media\/News\/Publishing | Facebook","cacheUrl":"http:\/\/www.google.com\/search?q=cache:_m-PNJ9c3sgJ:www.facebook.com","unescapedUrl":"https:\/\/www.facebook.com\/Pixelloid","url":"https:\/\/www.facebook.com\/Pixelloid","visibleUrl":"www.facebook.com"},{"content":"Welcome to the company profile of <b>Pixelloid<\/b> Studios Private Limited on LinkedIn.   <b>Pixelloid<\/b> is an award winning Content Creation Company with an active <b>...<\/b>","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid Studios Private Limited | LinkedIn","title":"<b>Pixelloid<\/b> Studios Private Limited | LinkedIn","cacheUrl":"http:\/\/www.google.com\/search?q=cache:vnyg3sUrGfgJ:www.linkedin.com","unescapedUrl":"http:\/\/www.linkedin.com\/company\/pixelloid-studios-private-limited","url":"http:\/\/www.linkedin.com\/company\/pixelloid-studios-private-limited","visibleUrl":"www.linkedin.com"},{"content":"The latest from <b>Pixelloid<\/b> (@<b>Pixelloid<\/b>). <b>Pixelloid<\/b> is an award winning 3D   Animation &amp; Visual Effects studio with a dedicated commercial training division.","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid (Pixelloid) on Twitter","title":"<b>Pixelloid<\/b> (<b>Pixelloid<\/b>) on Twitter","cacheUrl":"http:\/\/www.google.com\/search?q=cache:s4gJgJcovCsJ:twitter.com","unescapedUrl":"https:\/\/twitter.com\/Pixelloid","url":"https:\/\/twitter.com\/Pixelloid","visibleUrl":"twitter.com"},{"content":"Feb 10, 2013 <b>...<\/b> <b>Pixelloid<\/b>, Hyderabad is the only training institute in India that has an active   production environment. <b>Pixelloid&#39;s<\/b> courses are tailored to the <b>...<\/b>","GsearchResultClass":"GwebSearch","titleNoFormatting":"Pixelloid - Admission, Courses, Fee, Address | Pixelloid | Hyderabad ...","title":"<b>Pixelloid<\/b> - Admission, Courses, Fee, Address | <b>Pixelloid<\/b> | Hyderabad <b>...<\/b>","cacheUrl":"http:\/\/www.google.com\/search?q=cache:3OWFak05f30J:www.minglebox.com","unescapedUrl":"http:\/\/www.minglebox.com\/college\/pixelloid-Hyderabad","url":"http:\/\/www.mi
4

1 回答 1

1

您误解了 json 序列化对象的方式。基本上(非常基本上){...}是对象,[...,...]是数组并且key:value是对象属性,所以类似于:

{
  "responseData": {
     "results": [],
     "cursor": {
         "moreResultsUrl": "http://www.url.com",
         "searchResultTime": "0,00"
     }
  },
  "responseDetails": null,
  "responseStatus": 200
}

意味着您有一个具有 3 个属性的第一个对象:responseData(object)、responseDetails(null object) 和responseStatus(int)。AndresponseData是一个具有 2 个属性的对象:(results数组)和cursor(对象)。Andcursor的属性是moreResultsUrl(string) 和searchResultTime(string)。

现在,为了解析 json,你可以尝试这样的事情:

  • 请记住,您提供的代码过于克隆教程。您将不得不进行更多编辑,以保持一定程度的参数命名(您的变量谈论汽车,您的数据谈论网络搜索......)。您可以重命名方法中的一些数据ListAdapter adapter = new Simple...以满足您的需要。

** 为了使用这些 JSON 方法,您需要包含简单的 json 库。

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity { 

private Context context; 
private static String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=pixelloid&rsz=8";

private static final String TAG_content = "content";
private static final String TAG_GsearchResultClass = "GsearchResultClass";
private static final String TAG_titleNoFormatting = "titleNoFormatting";
private static final String TAG_title = "title";
private static final String TAG_cacheUrl = "cacheUrl";
private static final String TAG_unescapedUrl = "unescapedUrl";
private static final String TAG_url = "url";
private static final String TAG_visibleUrl = "visibleUrl";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ProgressTask(MainActivity.this).execute();
}

private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    private ListActivity activity;

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */

    /** application context. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter( context, contents, R.layout.list_item, 
                                    new String[] { TAG_title, TAG_content, TAG_url }, 
                                    new int[] { R.id.vehicleType, R.id.vehicleColor, R.id.fuel, R.id.treadType });

        setListAdapter(adapter);

        // selecting single ListView item
        //lv = getListView();
    }

    protected Boolean doInBackground(final String... args) {
            loadJson();
            return null;
    }
}

public static JSONObject parse() {
    JSONParser parser = new JSONParser();
    Object obj;
    JSONObject json = new JSONObject();
    try {
        obj = parser.getJSONFromUrl(url);
        json=(JSONObject)obj;
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return json;
}

private String moreResultsUrl = "";
private ArrayList<HashMap<String, String>> contents;

public void loadJson() {

    try {
        JSONObject obj = parse();
        if(obj!=null) {
             JSONObject responseData;
             responseData = (JSONObject ) obj.get("responseData");

             if(responseData !=null) {
                JSONArray results =  (JSONArray) obj.get("results"); 
                contents = new ArrayList<HashMap<String, String>>();

                HashMap<String, String> map;
                JSONObject cro;
                for(int i=0;i<results.length();i++) {
                    map = new HashMap<String, String>();
                    cro = (JSONObject) results.get(i);

                    map.put(TAG_content, cro.get(TAG_content).toString() );
                    map.put(TAG_GsearchResultClass, cro.get(TAG_GsearchResultClass).toString() );
                    map.put(TAG_titleNoFormatting, cro.get(TAG_titleNoFormatting).toString() );
                    map.put(TAG_titleNoFormatting, cro.get(TAG_titleNoFormatting).toString() );
                    map.put(TAG_title, cro.get(TAG_title).toString() );
                    map.put(TAG_cacheUrl, cro.get(TAG_cacheUrl).toString() );
                    map.put(TAG_unescapedUrl, cro.get(TAG_unescapedUrl).toString() );
                    map.put(TAG_url, cro.get(TAG_url).toString() );
                    map.put(TAG_visibleUrl, cro.get(TAG_visibleUrl).toString() );

                    contents.add(map);
                }

                JSONObject cursor =  (JSONObject ) responseData.get("cursor");
                if(cursor!=null)  moreResultsUrl = cursor.get("moreResultsUrl").toString();
             }
         }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

于 2013-10-04T12:12:58.510 回答