使用volley进行网络连接并解析JSON

时间:2014-04-13 06:36:00

标签: java android json

我使用VollyLibrary来解析JSON并将数据记录到Logconsole


我正在使用网址 :: http://www.androidbegin.com/tutorial/jsonparsetutorial.txt


JSON-响应::

{ 
"worldpopulation": 
    [
         {
         "rank":1,"country":"China",
         "population":"1,354,040,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/china.png"
         }, 

         {
         "rank":2,"country":"India",
         "population":"1,210,193,422",
         "flag":"http://www.androidbegin.com/tutorial/flag/india.png"
         }, 

         {
         "rank":3,"country":"United States",
         "population":"315,761,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
         }, 

         {
         "rank":4,"country":"Indonesia",
         "population":"237,641,326",
         "flag":"http://www.androidbegin.com/tutorial/flag/indonesia.png"
         }, 

         {
         "rank":5,"country":"Brazil",
         "population":"193,946,886",
         "flag":"http://www.androidbegin.com/tutorial/flag/brazil.png"
         }, 

         {
         "rank":6,"country":"Pakistan",
         "population":"182,912,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/pakistan.png"
         }, 

         {
         "rank":7,"country":"Nigeria",
         "population":"170,901,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/nigeria.png"
         }, 

         {
         "rank":8,"country":"Bangladesh",
         "population":"152,518,015",
         "flag":"http://www.androidbegin.com/tutorial/flag/bangladesh.png"
         }, 

         {
         "rank":9,"country":"Russia",
         "population":"143,369,806",
         "flag":"http://www.androidbegin.com/tutorial/flag/russia.png"
         }, 

         {
         "rank":10,"country":"Japan",
         "population":"127,360,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/japan.png"
         } 
    ] 
}

我面临的问题 ::

  1. 我能够获得JSON响应,但我无法记录数据 对于我在代码中发布的日志语句
  2. ex for below logs ::

     - Log.d(" - - value - - ", value.toString());
     - Log.d(" - - items - - ", items.toString());
     - Log.d(" - - item - - ", item.toString());
     - Log.d(" - - value.optString(rank) - - ",
           value.optString("rank").toString());
    

    MainActivity.java

    public class MainActivity extends Activity {
    
        //Declaring the variables
        private String TAG = this.getClass().getSimpleName();
        private ListView lstView;
        private RequestQueue mRequestQueue;
        private ArrayList<ModelClass> arrNews;
        private LayoutInflater li;
        private VollyAdapter va;
        private ProgressDialog pd;
        String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);
    
            li=LayoutInflater.from(this);
            arrNews=new ArrayList<ModelClass>();
            va=new VollyAdapter();
            lstView=(ListView) findViewById(R.id.listView);
    
            lstView.setAdapter(va);
    
            mRequestQueue =  Volley.newRequestQueue(this);
            pd = ProgressDialog.show(this,"Please Wait...","Please Wait...");
            try{
                Thread.sleep(2000);
            }catch(Exception e){
    
            }
    
            JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG,response.toString());
                    parseJSON(response);
                    va.notifyDataSetChanged();
                    pd.dismiss();
                    ;            }
            },new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i(TAG,error.getMessage());
                }
            });
            mRequestQueue.add(jr);
    
    
        }
    
        private void parseJSON(JSONObject response) {
            try{
                JSONObject value = response.getJSONObject("response");
                Log.d(" - - value - - ", value.toString());
                JSONArray items = value.getJSONArray("worldpopulation");
                Log.d(" - - items - - ", items.toString());
                for(int i=0;i<items.length();i++){
    
                    JSONObject item = items.getJSONObject(i);
                    Log.d(" - - item - - ", item.toString());
                    ModelClass nm = new ModelClass();
                    nm.setRank(value.optString("rank"));
                    Log.d(" - - value.optString(rank) - - ", value.optString("rank").toString());
                    nm.setCountry(value.optString("country"));
                    nm.setPopulation(value.optString("population"));
                    arrNews.add(nm);
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
    
    
    
        }
    
        class VollyAdapter extends BaseAdapter{
    
            @Override
            public int getCount() {
                return arrNews.size();
            }
    
            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return arrNews.get(position);
            }
    
            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder vh;
                if(convertView==null){
                    vh=new ViewHolder();
                    convertView=li.inflate(R.layout.row_listview, null);
                    vh.rank=(TextView) convertView.findViewById(R.id.txtRank);
                    vh.country=(TextView) convertView.findViewById(R.id.txtCountry);
                    vh.population=(TextView) convertView.findViewById(R.id.txtPopulation);
                    convertView.setTag(vh);
                }else{
                    vh=(ViewHolder) convertView.getTag();
                }
    
                ModelClass mc=arrNews.get(position);
                vh.rank.setText(mc.getRank());
                vh.country.setText(mc.getCountry());
                vh.population.setText(mc.getPopulation());
    
                return convertView;
            }
    
            class ViewHolder{
                TextView rank;
                TextView country;
                TextView population;
            }
    
        }
    
    }
    

    Logcat输出 ::

    04-13 11:57:24.825: I/ActivityManager(79): Displayed com.example.vollytestdev/.MainActivity: +5s99ms
    04-13 11:57:25.996: I/qtaguid(1251): Tagging socket 42 with tag 3ecd14a400000000(1053627556) for uid -1 failed errno=-2
    04-13 11:57:25.996: I/NetworkManagementSocketTagger(1251): tagSocketFd(42, 1053627556, -1) failed with errno-2
    04-13 11:57:27.915: D/Volley(1251): [109] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://www.androidbegin.com/tutorial/jsonparsetutorial.txt 0x3ecd14a4 NORMAL 1> [lifetime=3108], [size=1497], [rc=200], [retryCount=0]
    04-13 11:57:28.755: I/MainActivity(1251): {"worldpopulation":[{"rank":1,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/china.png","population":"1,354,040,000","country":"China"},{"rank":2,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/india.png","population":"1,210,193,422","country":"India"},{"rank":3,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/unitedstates.png","population":"315,761,000","country":"United States"},{"rank":4,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/indonesia.png","population":"237,641,326","country":"Indonesia"},{"rank":5,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/brazil.png","population":"193,946,886","country":"Brazil"},{"rank":6,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/pakistan.png","population":"182,912,000","country":"Pakistan"},{"rank":7,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/nigeria.png","population":"170,901,000","country":"Nigeria"},{"rank":8,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/bangladesh.png","population":"152,518,015","country":"Bangladesh"},{"rank":9,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/russia.png","population":"143,369,806","country":"Russia"},{"rank":10,"flag":"http:\/\/www.androidbegin.com\/tutorial\/flag\/japan.png","population":"127,360,000","country":"Japan"}]}
    04-13 11:57:28.765: W/System.err(1251): org.json.JSONException: No value for response
    04-13 11:57:28.775: W/System.err(1251):     at org.json.JSONObject.get(JSONObject.java:354)
    04-13 11:57:28.775: W/System.err(1251):     at org.json.JSONObject.getJSONObject(JSONObject.java:569)
    04-13 11:57:28.775: W/System.err(1251):     at com.example.vollytestdev.MainActivity.parseJSON(MainActivity.java:79)
    04-13 11:57:28.775: W/System.err(1251):     at com.example.vollytestdev.MainActivity.access$3(MainActivity.java:77)
    04-13 11:57:28.786: W/System.err(1251):     at com.example.vollytestdev.MainActivity$1.onResponse(MainActivity.java:62)
    04-13 11:57:28.786: W/System.err(1251):     at com.example.vollytestdev.MainActivity$1.onResponse(MainActivity.java:1)
    04-13 11:57:28.786: W/System.err(1251):     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
    04-13 11:57:28.786: W/System.err(1251):     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    04-13 11:57:28.795: W/System.err(1251):     at android.os.Handler.handleCallback(Handler.java:605)
    04-13 11:57:28.795: W/System.err(1251):     at android.os.Handler.dispatchMessage(Handler.java:92)
    04-13 11:57:28.805: W/System.err(1251):     at android.os.Looper.loop(Looper.java:137)
    04-13 11:57:28.815: W/System.err(1251):     at android.app.ActivityThread.main(ActivityThread.java:4340)
    04-13 11:57:28.825: W/System.err(1251):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-13 11:57:28.825: W/System.err(1251):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-13 11:57:28.825: W/System.err(1251):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-13 11:57:28.835: W/System.err(1251):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-13 11:57:28.845: W/System.err(1251):     at dalvik.system.NativeStart.main(Native Method)
    04-13 11:57:28.865: D/Volley(1251): [1] Request.finish: 4658 ms: [ ] http://www.androidbegin.com/tutorial/jsonparsetutorial.txt 0x3ecd14a4 NORMAL 1
    04-13 11:59:45.394: D/dalvikvm(296): GC_CONCURRENT freed 383K, 6% free 10316K/10951K, paused 13ms+8ms
    04-13 12:03:02.685: W/ThrottleService(79): unable to find stats for iface rmnet0
    

1 个答案:

答案 0 :(得分:1)

试试这个..

parseJSON(response.toString());

一样打电话
private void parseJSON(String response) {
   try{
       JSONObject value = new JSONObject(response);
       Log.d(" - - value - - ", value.toString());
       JSONArray items = value.getJSONArray("worldpopulation");
       Log.d(" - - items - - ", items.toString());
       for(int i=0;i<items.length();i++){

            JSONObject item = items.getJSONObject(i);
            Log.d(" - - item - - ", item.toString());
            ModelClass nm = new ModelClass();
            nm.setRank(item.optString("rank"));
            Log.d(" - - item.optString(rank) - - ", item.optString("rank").toString());
            nm.setCountry(item.optString("country"));
            nm.setPopulation(item.optString("population"));
            arrNews.add(nm);
        }
       }
       catch(Exception e){
           e.printStackTrace();
       }
}