1. 程式人生 > >android客戶端從伺服器端獲取json資料並解析

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<NameValuePair> 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<HashMap<String, Object>> Analysis(String jsonStr)
 7             throws JSONException {
 8         /******************* 解析 ***********************/
 9         JSONArray jsonArray = null;
10         // 初始化list陣列物件
11         ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
12         jsonArray = new JSONArray(jsonStr);
13         for (int i = 0; i < jsonArray.length(); i++) {
14             JSONObject jsonObject = jsonArray.getJSONObject(i);
15             // 初始化map陣列物件
16             HashMap<String, Object> map = new HashMap<String, Object>();
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<HashMap<String, Object>> it = allData.iterator();
 9             while (it.hasNext()) {
10                 Map<String, Object> 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<HashMap<String, Object>> 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<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
13         for(HashMap<String, Object> news : lists){
14             HashMap<String, Object> item = new HashMap<String, Object>();
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<HashMap<String, Object>> list;  
25     private int layoutID;  
26     private String flag[];  
27     private int ItemIDs[];  
28     public MySimpleAdapter1(Context context, List<HashMap<String, Object>> 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 }  
複製程式碼

ImageService工具類

複製程式碼
 1 package com.nuoter.adapterUntil;
 2 
 3