Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 從伺服器取得 JSON 並解析的完整流程

編輯:關於 Android 開發

本文整理 Android 客戶端向伺服器抓取 JSON 資料、解析、再綁定到介面的完整環節,分成四段:取資料、解析、資料適配、以及非同步處理。

一、取得 JSON 字串

做法一:HttpURLConnection

把串流逐段讀進 ByteArrayOutputStream,最後一次轉成字串。這是 JDK 自帶的方案,不需要額外依賴。

/**
 * 從指定的 URL 中取得資料
 * @param urlPath
 * @return
 * @throws Exception
 */
public static String readParse(String urlPath) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] data = new byte[1024];
    int len = 0;
    URL url = new URL(urlPath);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    InputStream inStream = conn.getInputStream();
    while ((len = inStream.read(data)) != -1) {
        outStream.write(data, 0, len);
    }
    inStream.close();
    return new String(outStream.toByteArray()); // 透過 toByteArray 取出寫入的內容
}

做法二:HttpClient(POST 帶參數)

需要送出表單參數時,用 HttpPost 搭配 UrlEncodedFormEntity 更直接。

/**
 * 訪問伺服器並回傳 JSON 字串
 *
 * @param params 傳給伺服器的參數
 * @param url
 * @return
 * @throws Exception
 */
public static String doPost(List<NameValuePair> params, String url) throws Exception {
    String result = null;
    // 取得 HttpClient 物件
    HttpClient httpClient = new DefaultHttpClient();
    // 建立 HttpPost 物件
    HttpPost httpPost = new HttpPost(url);
    if (params != null) {
        // 設定字元集
        HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        // 設定參數實體
        httpPost.setEntity(entity);
    }
    // 連接逾時與請求逾時可視需求開啟
    // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
    // httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    // 取得 HttpResponse 實例
    HttpResponse httpResp = httpClient.execute(httpPost);
    // 判斷是否請求成功
    if (httpResp.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
    } else {
        Log.i("HttpPost", "HttpPost 方式請求失敗");
    }
    return result;
}

補充一句:HttpClient 在 Android 5.1 之後已被標記為不再維護,新專案建議改用 HttpURLConnection 或 OkHttp。

二、解析 JSON

假設伺服器回傳的是這樣一個陣列:

json 資料:[{"id":"67","biaoTi":"G","logo":"https://www.nuoter.com/wtserver/resources/upload/13508741845270.png","logoLunbo":"https://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg","yuanJia":"0","xianJia":"0"},{"id":"64","biaoTi":"444","logo":"https://www.nuoter.com/wtserver/resources/upload/13508741704400.png","logoLunbo":"https://172.16.1.75:8080/wtserver/resources/upload/13508741738500.png","yuanJia":"0","xianJia":"0"},{"id":"62","biaoTi":"jhadasd","logo":"https://www.nuoter.com/wtserver/resources/upload/13508741500450.png","logoLunbo":"https://172.16.1.75:8080/wtserver/resources/upload/13508741557450.png","yuanJia":"1","xianJia":"0"}]

用內建的 org.json 逐筆取出,轉成 Map 清單:

/**
 * 解析
 *
 * @throws JSONException
 */
private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr) throws JSONException {
    /******************* 解析 ***********************/
    JSONArray jsonArray = null;
    // 初始化 list 陣列物件
    ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    jsonArray = new JSONArray(jsonStr);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        // 初始化 map 陣列物件
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("logo", jsonObject.getString("logo"));
        map.put("logoLunbo", jsonObject.getString("logoLunbo"));
        map.put("biaoTi", jsonObject.getString("biaoTi"));
        map.put("yuanJia", jsonObject.getString("yuanJia"));
        map.put("xianJia", jsonObject.getString("xianJia"));
        map.put("id", jsonObject.getInt("id"));
        list.add(map);
    }
    return list;
}

三、資料適配到介面

單純顯示在 TextView

/**
 * readParse(String) 從伺服器取得資料
 * Analysis(String) 解析 json 資料
 */
private void resultJson() {
    try {
        allData = Analysis(readParse(url));
        Iterator<HashMap<String, Object>> it = allData.iterator();
        while (it.hasNext()) {
            Map<String, Object> ma = it.next();
            if ((Integer) ma.get("id") == id) {
                biaoTi.setText((String) ma.get("biaoTi"));
                yuanJia.setText((String) ma.get("yuanJia"));
                xianJia.setText((String) ma.get("xianJia"));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

列表形式(ListView)

/**
 * ListView 資料適配
 */
private void product_data() {
    List<HashMap<String, Object>> lists = null;
    try {
        lists = Analysis(readParse(url)); // 解析出的 json 資料
    } catch (Exception e) {
        e.printStackTrace();
    }
    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
    for (HashMap<String, Object> news : lists) {
        HashMap<String, Object> item = new HashMap<String, Object>();
        item.put("chuXingTianShu", news.get("chuXingTianShu"));
        item.put("biaoTi", news.get("biaoTi"));
        item.put("yuanJia", news.get("yuanJia"));
        item.put("xianJia", news.get("xianJia"));
        item.put("id", news.get("id"));
        try {
            bitmap = ImageService.getImage(news.get("logo").toString()); // 圖片從伺服器取得
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            Log.i("bitmap", "" + bitmap);
            Toast.makeText(TravelLine.this, "圖片載入錯誤", Toast.LENGTH_SHORT).show();
        }
        item.put("logo", bitmap);
        data.add(item);
    }
    listItemAdapter = new MySimpleAdapter1(TravelLine.this, data, R.layout.a_travelline_item,
            // 動態陣列與子項的對應關係
            new String[] { "logo", "biaoTi", "xianJia", "yuanJia", "chuXingTianShu"},
            // 各子項對應的 view id
            new int[] { R.id.trl_ItemImage, R.id.trl_ItemTitle, R.id.trl_ItemContent, R.id.trl_ItemMoney, R.id.trl_Itemtoday});
    listview.setAdapter(listItemAdapter);
    // 加上點擊事件
    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            login_publicchannel_trl_sub(arg2);
        }
    });
}

四、自訂 Adapter 處理圖片欄位

由於清單裡混雜了圖片與文字,需要自己繼承 BaseAdapter,在 getView 中依欄位型別分別處理。

package com.nuoter.adapterUntil;

import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MySimpleAdapter1 extends BaseAdapter {
    private LayoutInflater mInflater;
    private List<HashMap<String, Object>> list;
    private int layoutID;
    private String flag[];
    private int ItemIDs[];

    public MySimpleAdapter1(Context context, List<HashMap<String, Object>> list, int layoutID, String flag[], int ItemIDs[]) {
        this.mInflater = LayoutInflater.from(context);
        this.list = list;
        this.layoutID = layoutID;
        this.flag = flag;
        this.ItemIDs = ItemIDs;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return 0;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = mInflater.inflate(layoutID, null);
        for (int i = 0; i < flag.length; i++) {
            if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) {
                ImageView imgView = (ImageView) convertView.findViewById(ItemIDs[i]);
                imgView.setImageBitmap((Bitmap) list.get(position).get(flag[i])); // 關鍵在這一行
            } else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) {
                TextView tv = (TextView) convertView.findViewById(ItemIDs[i]);
                tv.setText((String) list.get(position).get(flag[i]));
            }
        }
        return convertView;
    }
}

這裡有個值得優化的地方:每次 getView 都重新 inflate 佈局,長列表會明顯卡頓。實務上應該用 convertView 複用並搭配 ViewHolder 模式快取 findViewById 結果。

五、圖片下載工具類

JSON 裡的 logoLunbo 只是一個字串網址,需要另外抓圖。把這段邏輯抽到工具類中,各處都能共用。

package com.nuoter.adapterUntil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageService {
    /**
     * 取得網路圖片的資料
     * @param path 網路圖片路徑
     * @return
     */
    public static Bitmap getImage(String path) throws Exception {
        Bitmap bitmap = null;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 基於 HTTP 協定的連接物件
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream inStream = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(inStream);
        }
        return bitmap;
    }

    /**
     * 讀取串流中的資料
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] read(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}

如果調用處不多,也可以直接在 Activity 裡寫一個小函式:

/*
 * 從伺服器取圖片
 * 參數:String 類型
 * 回傳:Bitmap 類型
 */
public static Bitmap getHttpBitmap(String urlpath) {
    Bitmap bitmap = null;
    try {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        InputStream inputstream = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(inputstream);
        inputstream.close();
        conn.disconnect();
    } catch (Exception e) {
        Log.i("MyTag", "error:" + e.toString());
    }
    return bitmap;
}

調用方式:

public ImageView pic;
.....
allData = Analysis(readParse(url));
Iterator<HashMap<String, Object>> it = allData.iterator();
while (it.hasNext()) {
    Map<String, Object> ma = it.next();
    if ((Integer) ma.get("id") == id) {
        logo = (String) ma.get("logo");
        bigpic = getHttpBitmap(logo);
    }
}
pic.setImageBitmap(bigpic);

六、別忘了非同步

以上所有網路與解碼動作都不能放在主執行緒,否則會直接觸發 NetworkOnMainThreadException。資料量大或下載較慢時,開子執行緒搭配 Handler 回傳結果:

new Thread() {
    @Override
    public void run() {
        // 參數列表
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("currPage", Integer.toString(1)));
        nameValuePairs.add(new BasicNameValuePair("pageSize", Integer.toString(5)));
        try {
            String result = doPost(nameValuePairs, POST_URL);
            Message msg = handler.obtainMessage(1, 1, 1, result);
            handler.sendMessage(msg); // 發送訊息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}.start();

// 定義 Handler 物件
handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1: {
                // 處理 UI
                List<HashMap<String, Object>> lists = null;
                try {
                    lists = MainActivity.this.parseJson(msg.obj.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                for (HashMap<String, Object> news : lists) {
                    HashMap<String, Object> item = new HashMap<String, Object>();
                    item.put("id", news.get("id"));
                    item.put("ItemText0", news.get("name"));
                    try {
                        bitmap = ImageService.getImage(news.get("logo").toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (bitmap == null) {
                        Log.i("bitmap", "" + bitmap);
                        Toast.makeText(MainActivity.this, "圖片載入錯誤", Toast.LENGTH_SHORT).show();
                    }
                    item.put("ItemImage", bitmap);
                    data.add(item);
                }
                // 建立适配器,動態陣列元素與子項一一對應
                MySimpleAdapter saImageItems = new MySimpleAdapter(MainActivity.this, data,
                        R.layout.d_travelagence_item,
                        new String[] {"ItemImage", "ItemText0", "ItemText1"},
                        new int[] {R.id.lxs_item_image, R.id.lxs_item_text0, R.id.lxs_item_text1});
                gridview.setAdapter(saImageItems);
            }
            break;
            default:
                break;
        }
    }
};

整體回顧

把流程串起來就是:非同步請求 → 取得 JSON 字串 → 解析成物件集合 → 轉換成 Adapter 吃的形式 → 設定給 ListView 或 TextView。每一層都保持單一職責,後續要換網路庫或換解析框架時,改動範圍都能控制在一處。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved