android客户端从服务器端获取json数据并解析

今天总结一下:

首先客户端从服务器端获取json数据

1、利用HttpUrlConnection

 1 /**
 2      * 从指定的URL中获取数组
 3      * @param urlPath
 4      * @return
 5      * @throws Exception
 6      */
 7     public static String readParse(String urlPath) throws Exception {  
 8                ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
 9                byte[] data = new byte[1024];  
10                 int len = 0;  
11                 URL url = new URL(urlPath);  
12                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
13                 InputStream inStream = conn.getInputStream();  
14                 while ((len = inStream.read(data)) != -1) {  
15                     outStream.write(data, 0, len);  
16                 }  
17                 inStream.close();  
18                 return new String(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据  
19             }  

2、利用HttpClient

 1 /**
 2      * 访问数据库并返回JSON数据字符串
 3      * 
 4      * @param params 向服务器端传的参数
 5      * @param url
 6      * @return
 7      * @throws Exception
 8      */
 9     public static String doPost(List params, String url)
10             throws Exception {
11         String result = null;
12         // 获取HttpClient对象
13         HttpClient httpClient = new DefaultHttpClient();
14         // 新建HttpPost对象
15         HttpPost httpPost = new HttpPost(url);
16         if (params != null) {
17             // 设置字符集
18             HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
19             // 设置参数实体
20             httpPost.setEntity(entity);
21         }
22 
23         /*// 连接超时
24         httpClient.getParams().setParameter(
25                 CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
26         // 请求超时
27         httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
28                 3000);*/
29         // 获取HttpResponse实例
30         HttpResponse httpResp = httpClient.execute(httpPost);
31         // 判断是够请求成功
32         if (httpResp.getStatusLine().getStatusCode() == 200) {
33             // 获取返回的数据
34             result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
35         } else {
36             Log.i("HttpPost", "HttpPost方式请求失败");
37         }
38 
39         return result;
40     }

其次Json数据解析:
json数据:[{"id":"67","biaoTi":"G","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741845270.png","logoLunbo":"http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg","yuanJia":"0","xianJia":"0"},{"id":"64","biaoTi":"444","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741704400.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741738500.png","yuanJia":"0","xianJia":"0"},{"id":"62","biaoTi":"jhadasd","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741500450.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741557450.png","yuanJia":"1","xianJia":"0"}]

 

 1 /**
 2      * 解析
 3      * 
 4      * @throws JSONException
 5      */
 6     private static ArrayList> Analysis(String jsonStr)
 7             throws JSONException {
 8         /******************* 解析 ***********************/
 9         JSONArray jsonArray = null;
10         // 初始化list数组对象
11         ArrayList> list = new ArrayList>();
12         jsonArray = new JSONArray(jsonStr);
13         for (int i = 0; i < jsonArray.length(); i++) {
14             JSONObject jsonObject = jsonArray.getJSONObject(i);
15             // 初始化map数组对象
16             HashMap map = new HashMap();
17             map.put("logo", jsonObject.getString("logo"));
18             map.put("logoLunbo", jsonObject.getString("logoLunbo"));
19             map.put("biaoTi", jsonObject.getString("biaoTi"));
20             map.put("yuanJia", jsonObject.getString("yuanJia"));
21             map.put("xianJia", jsonObject.getString("xianJia"));
22             map.put("id", jsonObject.getInt("id"));
23             list.add(map);
24         }
25         return list;
26     }

 

 最后数据适配:

1、TextView

 1 /**
 2  * readParse(String)从服务器端获取数据
 3  * Analysis(String)解析json数据
 4  */
 5     private void resultJson() {
 6         try {
 7             allData = Analysis(readParse(url));
 8             Iterator> it = allData.iterator();
 9             while (it.hasNext()) {
10                 Map ma = it.next();
11                 if ((Integer) ma.get("id") == id) {
12                     biaoTi.setText((String) ma.get("biaoTi"));
13                     yuanJia.setText((String) ma.get("yuanJia"));
14                     xianJia.setText((String) ma.get("xianJia"));
15                 }
16             }
17         } catch (JSONException e) {
18             e.printStackTrace();
19         } catch (Exception e) {
20             e.printStackTrace();
21         }
22     }

2、ListView:

 1 /**
 2      * ListView 数据适配
 3      */
 4     private void product_data(){ 
 5         List> lists = null;
 6         try {
 7             lists = Analysis(readParse(url));//解析出json数据
 8         } catch (Exception e) {
 9             // TODO Auto-generated catch block
10             e.printStackTrace();
11         }
12         List> data = new ArrayList>();
13         for(HashMap news : lists){
14             HashMap item = new HashMap();
15             item.put("chuXingTianShu", news.get("chuXingTianShu"));
16             item.put("biaoTi", news.get("biaoTi"));
17             item.put("yuanJia", news.get("yuanJia"));
18             item.put("xianJia", news.get("xianJia"));
19             item.put("id", news.get("id"));
20             
21             try {
22                 bitmap = ImageService.getImage(news.get("logo").toString());//图片从服务器上获取
23             } catch (Exception e) {
24                 // TODO Auto-generated catch block
25                 e.printStackTrace();
26             }
27             if(bitmap==null){
28                 Log.i("bitmap", ""+bitmap);
29                 Toast.makeText(TravelLine.this, "图片加载错误", Toast.LENGTH_SHORT)
30                 .show();                                         // 显示图片编号
31             }
32             item.put("logo",bitmap);
33             data.add(item);
34         }
35              listItemAdapter = new MySimpleAdapter1(TravelLine.this,data,R.layout.a_travelline_item,
36                         // 动态数组与ImageItem对应的子项
37                         new String[] { "logo", "biaoTi",
38                                 "xianJia", "yuanJia", "chuXingTianShu"},
39                         // ImageItem的XML文件里面的一个ImageView,两个TextView ID
40                         new int[] { R.id.trl_ItemImage, R.id.trl_ItemTitle,
41                                 R.id.trl_ItemContent, R.id.trl_ItemMoney,
42                                 R.id.trl_Itemtoday});
43                 listview.setAdapter(listItemAdapter);
44                 //添加点击   
45                 listview.setOnItemClickListener(new OnItemClickListener() {    
46                     public void onItemClick(AdapterView arg0, View arg1, int arg2,   
47                             long arg3) {   
48                         login_publicchannel_trl_sub(arg2);
49                     }   
50                 });
51     }

对于有图片的要重写适配器

 1 package com.nuoter.adapterUntil;
 2 
 3 
 4 import java.util.HashMap;
 5 import java.util.List;
 6 
 7 
 8 import android.content.Context;
 9 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11 import android.graphics.Paint;
12 import android.net.Uri;
13 import android.view.LayoutInflater;
14 import android.view.View;
15 import android.view.ViewGroup;
16 import android.widget.BaseAdapter;
17 import android.widget.ImageView;
18 import android.widget.LinearLayout;
19 import android.widget.TextView;
20 
21 
22 public class MySimpleAdapter1 extends BaseAdapter {  
23     private LayoutInflater mInflater;  
24     private List> list;  
25     private int layoutID;  
26     private String flag[];  
27     private int ItemIDs[];  
28     public MySimpleAdapter1(Context context, List> list,  
29             int layoutID, String flag[], int ItemIDs[]) {  
30         this.mInflater = LayoutInflater.from(context);  
31         this.list = list;  
32         this.layoutID = layoutID;  
33         this.flag = flag;  
34         this.ItemIDs = ItemIDs;  
35     }  
36     @Override  
37     public int getCount() {  
38         // TODO Auto-generated method stub  
39         return list.size();  
40     }  
41     @Override  
42     public Object getItem(int arg0) {  
43         // TODO Auto-generated method stub  
44         return 0;  
45     }  
46     @Override  
47     public long getItemId(int arg0) {  
48         // TODO Auto-generated method stub  
49         return 0;  
50     }  
51     @Override  
52     public View getView(int position, View convertView, ViewGroup parent) {  
53         convertView = mInflater.inflate(layoutID, null);  
54        // convertView = mInflater.inflate(layoutID, null);  
55         for (int i = 0; i < flag.length; i++) {//备注1  
56             if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) {  
57                 ImageView imgView = (ImageView) convertView.findViewById(ItemIDs[i]);  
58                 imgView.setImageBitmap((Bitmap) list.get(position).get(flag[i]));///关键是这句!!!!!!!!!!!!!!!
59  
60             }else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) {  
61                 TextView tv = (TextView) convertView.findViewById(ItemIDs[i]);  
62                 tv.setText((String) list.get(position).get(flag[i]));  
63             }else{
64                 //...备注2 
65             }  
66         }  
67         //addListener(convertView); 
68         return convertView;  
69     }  
70 
71 /*    public void addListener(final View convertView) {
72         
73         ImageView imgView = (ImageView)convertView.findViewById(R.id.lxs_item_image);
74         
75         
76  
77     } */
78 
79 }  

对于图片的获取,json解析出来的是字符串url:"logoLunbo":http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg 从url获取 图片

ImageService工具类

 1 package com.nuoter.adapterUntil;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.InputStream;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 import android.graphics.Bitmap;
 9 import android.graphics.BitmapFactory;
10 
11 
12 public class ImageService {
13     
14     /**
15      * 获取网络图片的数据
16      * @param path 网络图片路径
17      * @return
18      */
19     public static Bitmap getImage(String path) throws Exception{
20         
21         /*URL url = new URL(imageUrl);   
22         HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
23         InputStream is = conn.getInputStream();   
24         mBitmap = BitmapFactory.decodeStream(is);*/
25         Bitmap bitmap= null;
26         URL url = new URL(path);
27         HttpURLConnection conn = (HttpURLConnection) url.openConnection();//基于HTTP协议连接对象
28         conn.setConnectTimeout(5000);
29         conn.setRequestMethod("GET");
30         if(conn.getResponseCode() == 200){
31             InputStream inStream = conn.getInputStream();
32             bitmap = BitmapFactory.decodeStream(inStream);
33         }
34         return bitmap;
35     }
36     
37     /**
38      * 读取流中的数据 从url获取json数据
39      * @param inStream
40      * @return
41      * @throws Exception
42      */
43     public static byte[] read(InputStream inStream) throws Exception{
44         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
45         byte[] buffer = new byte[1024];
46         int len = 0;
47         while( (len = inStream.read(buffer)) != -1){
48             outStream.write(buffer, 0, len);
49         }
50         inStream.close();
51         return outStream.toByteArray();
52     }
53 
54 
55 }

上面也将从url处获取网络数据写在了工具类ImageService中方面调用,因为都是一样的。

当然也可以在Activity类中写一个获取服务器图片的函数(当用处不多时)

 1  /*
 2 
 3      * 从服务器取图片
 4      * 参数:String类型
 5      * 返回:Bitmap类型
 6 
 7      */
 8 
 9     public static Bitmap getHttpBitmap(String urlpath) {
10         Bitmap bitmap = null;
11         try {
12             //生成一个URL对象
13             URL url = new URL(urlpath);
14             //打开连接
15             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
16 //            conn.setConnectTimeout(6*1000);
17 //            conn.setDoInput(true);
18             conn.connect();
19             //得到数据流
20             InputStream inputstream = conn.getInputStream();
21             bitmap = BitmapFactory.decodeStream(inputstream);
22             //关闭输入流
23             inputstream.close();
24             //关闭连接
25             conn.disconnect();
26         } catch (Exception e) {
27             Log.i("MyTag", "error:"+e.toString());
28         }
29         return bitmap;
30     }

调用:

 1 public ImageView pic;
 2 .....
 3 .....
 4 allData=Analysis(readParse(url));
 5 Iterator> it=allData.iterator();
 6 while(it.hasNext()){
 7 Map ma=it.next();
 8 if((Integer)ma.get("id")==id)
 9 {
10 logo=(String) ma.get("logo");
11 bigpic=getHttpBitmap(logo);
12 }
13 }
14 pic.setImageBitmap(bigpic);

另附 下载数据很慢时建立子线程并传参:

 1 new Thread() {
 2             @Override
 3             public void run() {
 4                 // 参数列表
 5                 List nameValuePairs = new ArrayList();
 6                 nameValuePairs.add(new BasicNameValuePair("currPage", Integer
 7                         .toString(1)));
 8                 nameValuePairs.add(new BasicNameValuePair("pageSize", Integer
 9                         .toString(5)));
10                 try {
11                     String result = doPost(nameValuePairs, POST_URL);                    
12                     Message msg = handler.obtainMessage(1, 1, 1, result);
13                     handler.sendMessage(msg);                     // 发送消息
14                 } catch (Exception e) {
15                     // TODO Auto-generated catch block
16                     e.printStackTrace();
17                 }
18             }
19         }.start();
20 
21         // 定义Handler对象
22         handler = new Handler() {
23             public void handleMessage(Message msg) {
24                 switch (msg.what) {
25                 case 1:{
26                     // 处理UI
27                     StringBuffer strbuf = new StringBuffer();
28                     List> lists = null;
29                     try {
30                         lists = MainActivity.this
31                                 .parseJson(msg.obj.toString());
32                     } catch (Exception e) {
33                         // TODO Auto-generated catch block
34                         e.printStackTrace();
35                     }
36                     List> data = new ArrayList>();
37                     for(HashMap news : lists){
38                         HashMap item = new HashMap();
39                         item.put("id", news.get("id"));
40                         item.put("ItemText0", news.get("name"));
41                         
42                         try {
43                             bitmap = ImageService.getImage(news.get("logo").toString());
44                         } catch (Exception e) {
45                             // TODO Auto-generated catch block
46                             e.printStackTrace();
47                         }
48                         if(bitmap==null){
49                             Log.i("bitmap", ""+bitmap);
50                             Toast.makeText(MainActivity.this, "图片加载错误", Toast.LENGTH_SHORT)
51                             .show();                                         // 显示图片编号
52                         }
53                         item.put("ItemImage",bitmap);
54                         data.add(item);
55                     }
56                     
57                     //生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
58                     MySimpleAdapter saImageItems = new MySimpleAdapter(MainActivity.this, data, 
59                             R.layout.d_travelagence_item, 
60                             new String[] {"ItemImage", "ItemText0", "ItemText1"}, 
61                             new int[] {R.id.lxs_item_image, R.id.lxs_item_text0, R.id.lxs_item_text1});
62                     //添加并且显示
63                     gridview.setAdapter(saImageItems);
64                 }
65                     break;
66                 default:
67                     break;
68                 }
69                 
70                 
71             }
72         };

 

 

你可能感兴趣的:(android客户端从服务器端获取json数据并解析)