用Gson解析json数据

1、假设服务器返回给我们的json数据如下:

{
    "tag1": "美女",
    "tag2": "全部",
    "totalNum": 16851,
    "start_index": 0,
    "return_number": 2,
    "data": [
        {
            "id": "11517537470",
            "pn": 0,
            "abs": "情人结",               
            "tag": "全部",
            "date": "2016-01-26",
            "image_url": "http://g.hiphotos.baidu.com/image/pic/item/08f790529822720eb25fa86479cb0a46f31fab9f.jpg",
            "user_id": "3156953030",
            "colum": "美女",
            "photo_id": "11517537470",
        },
        {
            "id": "9476524190",
            "pn": 1,
            "abs": "纯情美女洁白私房照",
            "tag": "全部",
            "date": "2016-01-26",
            "image_url": "http://g.hiphotos.baidu.com/image/pic/item/4a36acaf2edda3cce291552403e93901213f92b9.jpg",
            "user_id": "862755774",
            "colum": "美女",
            "photo_id": "9476524190",
        },
    ]
}

2、把gson的jar包导入工程内(jar包自行下载)
3、根据json返回的数据编写对应的bean,由上面的的json数据编写的对应的bean文件为:(不想要的字段可以不写;eg:不想要返回的id,则就不用在bean文件中写id这个字段)

import java.util.ArrayList;

public class NetData {
    public ArrayList data;

    public class Desc {
        public String id;
        public String pn;
        public String abs;
        public String tag;
        public String image_url;
        public String user_id;
        public String colum;
        public String photo_id;

        @Override
        public String toString() {
            return "Desc [id=" + id + ", pn=" + pn + ", abs=" + abs + ", tag=" + tag + ", image_url=" + image_url
                    + ", user_id=" + user_id + ", colum=" + colum + ", photo_id=" + photo_id + "]";
        }
    }

    public String return_number;
    public String start_index;
    public String tag1;
    public String tag2;
    public String totalNum;

    @Override
    public String toString() {
        return "NetData [data=" + data + ", return_number=" + return_number + ", start_index=" + start_index
                + ", tag1=" + tag1 + ", tag2=" + tag2 + ", totalNum=" + totalNum + "]";
    }

}

3、解析

Gson gson = new Gson();
NetData data = gson.fromJson(json, NetData.class);
//然后就可以这样操作数据了
List<Desc>list = new ArrayList<Desc>();
list=data.data;
String return_number = data.return_number;

你可能感兴趣的:(用Gson解析json数据)