类似于解析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;

    }

}

好了。这时候已经可以实现这个功能了。

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐