1. 程式人生 > >Gson的使用——Gson解析json陣列並展示在ListView控制元件上

Gson的使用——Gson解析json陣列並展示在ListView控制元件上

類似於解析json資料的框架有很多,常用的就是Gson,使用起來特別的方便,同時,還擁有很好的可操作性,今天就來說說怎麼用Gson去解析一個json陣列。使用Gson之前,需要下載一個gson.jar的jar包。具體的自己去網上下載,有很多。

首先看看資料來源

{
    "a": [
        {
            "numid": "1",
            "name": "艾勇",
            "abbreviation": "aiyong",
            "photo": "/test/qingqixie/Public/Upload/niul7b2sdy.jpg"
}, { "numid": "2", "name": "安京哲", "abbreviation": "anjingzhe", "photo": "/test/qingqixie/Public/Upload/tfnc4pko7n11ul.jpg" } ]
, "b": [ { "numid": "351", "name": "白雪劍", "abbreviation
": "baixuejian", "photo": "/test/qingqixie/Public/Upload/31dl12sfmjo.png" }, { "numid": "3", "name": "白振亮", "abbreviation": "baizhenliang", "photo": "/test/qingqixie/Public/Upload/rrqixinqap.jpg" }, { "numid
": "4", "name": "畢偉", "abbreviation": "biwei", "photo": "/test/qingqixie/Public/Upload/7rhytjvhmg8q.jpg" } ]
, "c": [ { "numid": "5", "name": "曹恆海", "abbreviation": "caohenghai", "photo": "/test/qingqixie/Public/Upload/0iru1ef1w0k58.jpg" }, { "numid": "6", "name": "曹潤星", "abbreviation": "caorunxing", "photo": "/test/qingqixie/Public/Upload/mdk1rliogrk.jpg" }, { "numid": "377", "name": "曹顯龍", "abbreviation": "caoxianlong", "photo": "" }, { "numid": "447", "name": "測試使用者", "abbreviation": "ceshiyonghu", "photo": "" }, { "numid": "456", "name": "測試專員", "abbreviation": "ceshizhuanyuan", "photo": "" }, { "numid": "7", "name": "柴寧", "abbreviation": "chaining", "photo": "/test/qingqixie/Public/Upload/nqyrnb2gahql.jpg" }, { "numid": "8", "name": "常傳泉", "abbreviation": "changchuanquan", "photo": "/test/qingqixie/Public/Upload/rbbf5xpwn7a.jpg" }, { "numid": "453", "name": "查芃", "abbreviation": "chapeng", "photo": "" }, { "numid": "13", "name": "陳鍇", "abbreviation": "chen", "photo": "" }, { "numid": "16", "name": "陳琪", "abbreviation": "chen", "photo": "/test/qingqixie/Public/Upload/agogbyaf9tmfwjqf.jpg" }, { "numid": "10", "name": "陳飛", "abbreviation": "chenfei", "photo": "/test/qingqixie/Public/Upload/pi6aa9p5q7envo2k.jpg" }, { "numid": "413", "name": "成建新", "abbreviation": "chengjianxin", "photo": "" }, { "numid": "21", "name": "程晟", "abbreviation": "chengsheng", "photo": "/test/qingqixie/Public/Upload/hkthw4jent6czg.jpg" }, { "numid": "22", "name": "程樹森", "abbreviation": "chengshusen", "photo": "/test/qingqixie/Public/Upload/kf7278h7t832u6.jpg" }, { "numid": "458", "name": "程式設計師", "abbreviation": "chengxuyuan", "photo": "" }, { "numid": "11", "name": "陳海濱", "abbreviation": "chenhaibin", "photo": "" }, { "numid": "432", "name": "陳捷", "abbreviation": "chenjie", "photo": "" }, { "numid": "12", "name": "陳津川", "abbreviation": "chenjinchuan", "photo": "/test/qingqixie/Public/Upload/59amjj1fe3f.jpg" }, { "numid": "14", "name": "陳娜娜", "abbreviation": "chennana", "photo": "/test/qingqixie/Public/Upload/fq82mj0xpt.jpg" }, { "numid": "15", "name": "陳鵬", "abbreviation": "chenpeng", "photo": "" }, { "numid": "17", "name": "陳青溪", "abbreviation": "chenqingxi", "photo": "/test/qingqixie/Public/Upload/r9a3wtcf88b.jpg" }, { "numid": "19", "name": "陳奕超", "abbreviation": "chenyichao", "photo": "/test/qingqixie/Public/Upload/izsp4r3yx.jpg" }, { "numid": "20", "name": "陳宗敏", "abbreviation": "chenzongmin", "photo": "/test/qingqixie/Public/Upload/syewiyta6g42cv8.jpg" }, { "numid": "9", "name": "車永超", "abbreviation": "cheyongchao", "photo": "/test/qingqixie/Public/Upload/sj68k9ope6r.jpg" }, { "numid": "23", "name": "遲迅", "abbreviation": "chixun", "photo": "" }, { "numid": "24", "name": "褚海濤", "abbreviation": "chuhaitao", "photo": "/test/qingqixie/Public/Upload/8bwltpuwf.jpg" }, { "numid": "26", "name": "崔鳳祥", "abbreviation": "cuifengxiang", "photo": "/test/qingqixie/Public/Upload/g48ihbkfd2itf43.jpg" }, { "numid": "27", "name": "崔錦鋒", "abbreviation": "cuijinfeng", "photo": "" }, { "numid": "28", "name": "崔亞強", "abbreviation": "cuiyaqiang", "photo": "/test/qingqixie/Public/Upload/jcpfeegotnik1pp.jpg" }, { "numid": "397", "name": "崔藝", "abbreviation": "cuiyi", "photo": "/test/qingqixie/Public/Upload/3kt4hrsm3qmfb5.jpg" } ], "d": [ { "numid": "29", "name": "戴新民", "abbreviation": "daixinmin", "photo": "/test/qingqixie/Public/Upload/vnndoq3rw8ekk.jpg" }, { "numid": "30", "name": "鄧麗", "abbreviation": "dengli", "photo": "/test/qingqixie/Public/Upload/hnow6jn58k.jpg" }, { "numid": "32", "name": "丁煒", "abbreviation": "dingwei", "photo": "/test/qingqixie/Public/Upload/qt9tsrsied.jpg" }, { "numid": "440", "name": "董夢石", "abbreviation": "dongmengshi", "photo": "/test/qingqixie/Public/Upload/r0vsa2w39xq07.png" }, { "numid": "33", "name": "杜鍇", "abbreviation": "du", "photo": "/test/qingqixie/Public/Upload/ytig406nljeyef.jpg" }, { "numid": "34", "name": "段寶平", "abbreviation": "duanbaoping", "photo": "/test/qingqixie/Public/Upload/rv7az0zbo.jpg" }, { "numid": "35", "name": "段海鷹", "abbreviation": "duanhaiying", "photo": "/test/qingqixie/Public/Upload/xbquyz6kmga28.jpg" }, { "numid": "36", "name": "段江", "abbreviation": "duanjiang", "photo": "" }, { "numid": "403", "name": "段煉", "abbreviation": "duanlian", "photo": "/test/qingqixie/Public/Upload/curi2er7ti.jpg" }, { "numid": "37", "name": "段拓文", "abbreviation": "duantuowen", "photo": "/test/qingqixie/Public/Upload/jstsdb0afmu4xha.jpg" } ] }

這個是一個比較具有代表性的json資料。先大體的分析一下資料,最外面的是一個json物件,裡面有四個json陣列。那麼進行第一、步,先建立實體類,當然了,這麼多的資料,不可能讓我們一個個的去寫,我們這裡要引用一個工具,他會幫我生成實體類。
網址如下:http://www.bejson.com/json2javapojo/

這裡為了方便,我就把這個資料放在了assets目錄下,取名為text.txt 。

好了,資料來源有了,實體類也建好了,那麼就可以開始我們的編碼了。首先是從assets取出資料,程式碼如下:

try {
    String data;
    InputStream is;
    is=getResources().getAssets().open("text.txt");
            byte[] b = new byte[is.available()];
            is.read(b);
            data = new String(b);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

這個data就是我們的json資料了,接下來就是實現解析的操作了。這裡我寫成了一個方法。具體程式碼如下:

/*
     * 解析資料
     */
    public void analysisData(String data) {
        try {
            // Type listType = new TypeToken<List<Root>>() {
            // }.getType();
            oList = new ArrayList<Map<String, Object>>();
            List<Root> appinfos = new ArrayList<Root>();
            Root depts = gson.fromJson(data, Root.class);
            appinfos.add(depts);

            for (int i = 0; i < appinfos.size(); i++) {

                root = appinfos.get(i);
                List<A> listA = new ArrayList<A>();
                List<B> listB = new ArrayList<B>();

                listA = root.getA();
                for (int j = 0; j < listA.size(); j++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    a = listA.get(j);

                    map.put("name", a.getName());
                    map.put("photo", a.getPhoto());
                    oList.add(map);
                }
                listB = root.getB();
                oList2 = new ArrayList<Map<String, Object>>();
                for (int j = 0; j < listB.size(); j++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    b = listB.get(j);

                    map.put("name", b.getName());
                    map.put("photo", b.getPhoto());
                    oList2.add(map);
                }
                oList.addAll(oList2);

            }

            mListView.setAdapter(new MyAdapter(oList, this));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

截止目前,這些資料就解析完成了。當然,可能看起來雲裡霧裡,下面貼上所有的程式碼:
佈局檔案:activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dip" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名:"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="18sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="照片:"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/photo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

1.MainActivity.java

public class MainActivity extends Activity {

    private String data;
    private Gson gson;
    private Root root;
    private A a;
    private B b;
    private ListView mListView;
    private List<Map<String, Object>> oList;
    private List<Map<String, Object>> oList2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listview);
        gson = new Gson();
        a = new A();
        b = new B();
        root = new Root();
        try {
            InputStream is = getResources().getAssets().open("text.txt");
            byte[] b = new byte[is.available()];
            is.read(b);
            data = new String(b);
            analysisData(data);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * 解析資料
     */
    public void analysisData(String data) {
        try {
            // Type listType = new TypeToken<List<Root>>() {
            // }.getType();
            oList = new ArrayList<Map<String, Object>>();
            List<Root> appinfos = new ArrayList<Root>();
            Root depts = gson.fromJson(data, Root.class);
            appinfos.add(depts);

            for (int i = 0; i < appinfos.size(); i++) {

                root = appinfos.get(i);
                List<A> listA = new ArrayList<A>();
                List<B> listB = new ArrayList<B>();

                listA = root.getA();
                for (int j = 0; j < listA.size(); j++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    a = listA.get(j);

                    map.put("name", a.getName());
                    map.put("photo", a.getPhoto());
                    oList.add(map);
                }
                listB = root.getB();
                oList2 = new ArrayList<Map<String, Object>>();
                for (int j = 0; j < listB.size(); j++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    b = listB.get(j);

                    map.put("name", b.getName());
                    map.put("photo", b.getPhoto());
                    oList2.add(map);
                }
                oList.addAll(oList2);

            }

            mListView.setAdapter(new MyAdapter(oList, this));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

實體類的程式碼如下:
A.java

public class A {
    private String numid;

    private String name;

    private String abbreviation;

    private String photo;

    public void setNumid(String numid) {
        this.numid = numid;
    }

    public String getNumid() {
        return this.numid;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return this.abbreviation;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

    public String getPhoto() {
        return this.photo;
    }

}

B、C、D的跟A一樣,就不再贅述了。

還有一個Roor.java:

public class Root {
    private List<A> a;

    private List<B> b;

    private List<C> c;

    private List<D> d;

    public void setA(List<A> a) {
        this.a = a;
    }

    public List<A> getA() {
        return this.a;
    }

    public void setB(List<B> b) {
        this.b = b;
    }

    public List<B> getB() {
        return this.b;
    }

    public void setC(List<C> c) {
        this.c = c;
    }

    public List<C> getC() {
        return this.c;
    }

    public void setD(List<D> d) {
        this.d = d;
    }

    public List<D> getD() {
        return this.d;
    }

}

介面卡程式碼:MAdapter.java

public class MyAdapter extends BaseAdapter {

    private List<Map<String, Object>> roots;

    private Context mContext;

    private LayoutInflater inflater;

    private Root root;

    public MyAdapter(List<Map<String, Object>> roots, Context mContext) {
        this.roots = roots;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
    }

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

    @Override
    public Object getItem(int position) {
        return roots.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        viewHonder honder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item, null);
            honder = new viewHonder();
            honder.mName = (TextView) convertView.findViewById(R.id.name);
            honder.mPhoto = (TextView) convertView.findViewById(R.id.photo);
            convertView.setTag(honder);
        } else {
            honder = (viewHonder) convertView.getTag();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map = roots.get(position);
        honder.mName.setText(map.get("name") + "");
        honder.mPhoto.setText(map.get("photo") + "");
        return convertView;
    }

    class viewHonder {
        TextView mName;
        TextView mPhoto;

    }

}

好了。這時候已經可以實現這個功能了。