天天看點

Android學習之Json解析庫Gson

接着上一篇Volley,在使用Volley加載好資料之後,我們肯定不能直接使用這個資料,一般擷取的資料都會是Json格式,是以自然而然我們要處理下Json,網絡上有很多Json解析庫,這裡我使用Gson來解析Json,Gson有個特點,就是要将資料的鍵作為變量封裝到一個個實體中,如果值為數組的,變量的類型還必須是集合,然後通過Gson.fromJson來傳入資料和實體類,再通過實體類的get方法來擷取我們想要的資料,可以說是一個先苦後甜的過程。Gson其實用起來是很友善的,可能第一次覺得有點麻煩,用習慣了就發現它的好處了。廢話不多說了,看個簡單的Demo:

首先是導入Gson的Jar包,這裡我用了gson-2.6.2.jar,講其放入libs中,然後右鍵Add As Library即可,下載下傳位址:

http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.6.2%7Cjar

首先看下完整的資料:

{

    "rating": {

        "max": 10,

        "numRaters": 348,

        "average": "7.0",

        "min": 0

    },

    "subtitle": "",

    "author": [

        "[日] 片山恭一"

    ],

    "pubdate": "2005-1",

    "tags": [

        {

            "count": 138,

            "name": "片山恭一",

            "title": "片山恭一"

        },

        {

            "count": 65,

            "name": "日本",

            "title": "日本"

        },

        {

            "count": 61,

            "name": "日本文學",

            "title": "日本文學"

        },

        {

            "count": 38,

            "name": "小說",

            "title": "小說"

        },

        {

            "count": 32,

            "name": "滿月之夜白鲸現",

            "title": "滿月之夜白鲸現"

        },

        {

            "count": 15,

            "name": "愛情",

            "title": "愛情"

        },

        {

            "count": 8,

            "name": "純愛",

            "title": "純愛"

        },

        {

            "count": 8,

            "name": "外國文學",

            "title": "外國文學"

        }

    ],

    "origin_title": "",

    "image": "https://img1.doubanio.com/mpic/s1747553.jpg",

    "binding": "平裝",

    "translator": [

        "豫人"

    ],

    "catalog": "\n      ",

    "pages": "180",

    "images": {

        "small": "https://img1.doubanio.com/spic/s1747553.jpg",

        "large": "https://img1.doubanio.com/lpic/s1747553.jpg",

        "medium": "https://img1.doubanio.com/mpic/s1747553.jpg"

    },

    "alt": "http://book.douban.com/subject/1220562/",

    "id": "1220562",

    "publisher": "青島出版社",

    "isbn10": "7543632608",

    "isbn13": "9787543632608",

    "title": "滿月之夜白鲸現",

    "url": "http://api.douban.com/v2/book/1220562",

    "alt_title": "",

    "author_intro": "",

    "summary": "那一年,是聽莫紮特、釣鲈魚和家庭破裂的一年。說到家庭破裂,母親怪自己當初沒有找到好男人,父親則認為當時是被狐狸精迷住了眼,失常的是母親,但出問題的是父親……。",

    "price": "15.00元"

}

接下來是實體:

/**
 * tags
 *
 * @author yuzhentao
 */
public class Tag {

    private String count;
    private String name;
    private String title;

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public String getName() {
        return name;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}      
/**
 * Book
 *
 * @author yuzhentao
 */
public class Book {

    private String title;
    private String publisher;
    private String summary;
    private ArrayList<Tag> tags;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public ArrayList<Tag> getTags() {
        return tags;
    }

    public void setTags(ArrayList<Tag> tags) {
        this.tags = tags;
    }

}      

接下來是主界面:

/**
 * 主界面
 *
 * @author yuzhentao
 */
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button_activity_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
    }

    /**
     * 擷取資料
     */
    private void getData() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "https://api.douban.com/v2/book/1220562";
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("yuzhentao", "擷取成功=" + response);
                dealData(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("yuzhentao", "擷取失敗=" + error);
            }
        });
        requestQueue.add(request);
    }

    /**
     * 處理資料
     *
     * @param result:String
     */
    private void dealData(String result) {
        Gson gson = new Gson();
        Book book = gson.fromJson(result, Book.class);
        Log.e("yuzhentao", book.getTitle() + ":" + book.getPublisher() + ":" + book.getTags().size());
    }

}      

最後是效果,這裡直接列印Log:

03-05 10:04:50.719 26924-26924/yuzhentao.gsondemo E/yuzhentao: 滿月之夜白鲸現:青島出版社:8

Demo位址:http://download.csdn.net/detail/qq_23940659/9467050