[转载]android通过httpClient请求获取JSON数据并且解析 - KimhillZhang - 博客园

[转载]android通过httpClient请求获取JSON数据并且解析 – KimhillZhang – 博客园.

使用.net创建一个ashx文件,并response.write json格式

public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            StringBuilder  jsonBuilder  = new StringBuilder();

            jsonBuilder.Append("{\"parent\":");

            jsonBuilder.Append("{\"children\":");

            jsonBuilder.Append("[");

            jsonBuilder.Append("{\"id\":\"11111\",\"title\":\"aaaaaaa\",\"name\":\"111111111aaaaaaaaaa\"},");

            jsonBuilder.Append("{\"id\":\"22222\",\"title\":\"bbbbbbb\",\"name\":\"222222222aaaaaaaaaa\"},");

            jsonBuilder.Append("{\"id\":\"33333\",\"title\":\"ccccccc\",\"name\":\"33333333aaaaaaaaaa\"}");

            jsonBuilder.Append("]}}");

 

            context.Response.Write(jsonBuilder.ToString());

        }

Android代码

public class HttpClient_Get_Activity extends Activity {

   public TextView myTextView = null;

   @Override

   protected void onCreate(Bundle savedInstanceState) {

      // TODO Auto-generated method stub

      super.onCreate(savedInstanceState);

      this.setContentView(R.layout.httpget_httpclient_activity);

     

      Button btn = (Button)this.findViewById(R.id.button1);

      btn.setOnClickListener(new Button.OnClickListener(){

 

         @Override

         public void onClick(View v) {

              new ReadHttpGet().execute("http://190.160.10.79:7890/handler1.ashx");

         }

        

      });

   }

    class ReadHttpGet extends AsyncTask<Object, Object, Object>

    {

 

      @Override

      protected Object doInBackground(Object... params) {

         // TODO Auto-generated method stub

        

         HttpGet httpRequest = new HttpGet(params[0].toString());

         try

         {

            HttpClient httpClient = new DefaultHttpClient();

            HttpResponse httpResponse = httpClient.execute(httpRequest);

           

            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

            {

                String strResult = EntityUtils.toString(httpResponse.getEntity());

                return strResult;

            }

            else

            {

                return "请求出错";

            }

         }

         catch(ClientProtocolException e)

         {

           

         }

         catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

         }

        

         return null;

      }

 

      @Override

      protected void onCancelled(Object result) {

         // TODO Auto-generated method stub

         super.onCancelled(result);

      }

 

      @Override

      protected void onPostExecute(Object result) {

         // TODO Auto-generated method stub

         super.onPostExecute(result);

        

         try

         {

            //创建一个JSON对象

            JSONObject jsonObject = new JSONObject(result.toString()).getJSONObject("parent");

            //获取某个对象的JSON数组

            JSONArray jsonArray = jsonObject.getJSONArray("children");

           

            StringBuilder builder = new StringBuilder();

           

            for(int i = 0; i<jsonArray.length(); i++)

            {

                //新建一个JSON对象,该对象是某个数组里的其中一个对象

                JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);

               

                builder.append(jsonObject2.getString("id")); //获取数据

                builder.append(jsonObject2.getString("title"));

                builder.append(jsonObject2.getString("name"));

            }

            myTextView.setText(builder.toString());

         }

         catch (JSONException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

         }

        

      }

 

      @Override

      protected void onPreExecute() {

         // TODO Auto-generated method stub

         //super.onPreExecute();

         Toast.makeText(getApplicationContext(), "开始HTTP GET请求", Toast.LENGTH_LONG).show();

      }

 

      @Override

      protected void onProgressUpdate(Object... values) {

         // TODO Auto-generated method stub

         super.onProgressUpdate(values);

      }

      

    }

}

Android中json的浅薄理解

JSONObject 表示形式 {“key” : “value”}

JSONArray 表示形式 [{“key” : “value”},{“key” : “value”},{“key” : “value”}],JSONArray里面包含多个JSONObject

访问时通过 JSONObject对象去访问,使用 jsonObject.getXXX(“key”)得到相应的值

一般解析JSON都使用这两个。

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏