Android JSON 解析庫的使用 - Gson 和 fast-json

來源:互聯網
上載者:User

標籤:

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。它基於ECMAScript的一個子集。
JSON採用完全獨立於語言的文字格式設定,但是也使用了類似於C語言家族的習慣(包括C、C++、C#、Java、JavaScript、Perl、Python等)。
這些特性使JSON成為理想的資料交換語言。 易於人閱讀和編寫,同時也易於機器解析和產生(網路傳輸速率)。

 

GSON是由Google官方推出的 JSON 與 Java 對象轉化的 Java類庫

fast-json 阿里推出的用於Android平台的庫,效能很好的Java實現的JSON 解析和產生器,據說功能強大且速度超越現有的所有庫

 

GSON用法:

1. 解析JSONObject,JSONArray

2. 將JSON實體轉化為JSON資料

工程匯入三個包 fastjson, gson,volley


//從豆瓣網擷取資料, 在 http://www.bejson.com/ 解析查看資料private void getData() {    StringRequest request = new StringRequest(url, new Listener<String>() {        @Override        public void onResponse(String arg0) {            Log.i(TAG, arg0); //擷取完成後,在 http://www.bejson.com/ 解析查看資料            dealData(arg0);        }    }, new ErrorListener() {        @Override        public void onErrorResponse(VolleyError arg0) {            // TODO Auto-generated method stub        }    });    new Volley().newRequestQueue(getApplicationContext()).add(request);}//處理資料private void dealData(String result){    Gson gson = new Gson();    Book book = gson.fromJson(result, Book.class); // data 轉實體    Log.i(TAG, book.getTitle() + "; "            + book.getPublisher() + ";"            + book.getTags().size() + ";" );}

 

private String TAG = "CARLOZ";private String url = "https://api.douban.com/v2/book/1220562";@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_jsonparse);        getData(); }

Book屬於實體類,詳情,請查看代碼GitHub

 

輸出結果

08-10 21:19:22.321: I/CARLOZ(24911): {"rating":{"max":10,"numRaters":340,"average":"7.0","min":0},"subtitle":"","author":["[日] 片山恭一"],"pubdate":"2005-1","tags":[{"count":133,"name":"片山恭一","title":"片山恭一"},{"count":62,"name":"日本","title":"日本"},{"count":60,"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":"http:\/\/img3.douban.com\/mpic\/s1747553.jpg","binding":"平裝","translator":["豫人"],"catalog":"\n      ","pages":"180","images":{"small":"http:\/\/img3.douban.com\/spic\/s1747553.jpg","large":"http:\/\/img3.douban.com\/lpic\/s1747553.jpg","medium":"http:\/\/img3.douban.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元"}08-10 21:19:22.371: I/CARLOZ(24911): 滿月之夜白鯨現; 青島出版社;8;

 

Fast-json

public class FastJsonParseActivity extends Activity {        private String TAG = "CARLOZ";    private String url = "https://api.douban.com/v2/book/1220562";        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_fast_json_parse);                getData();    }    private void getData() {        StringRequest request = new StringRequest(url, new Listener<String>() {            @Override            public void onResponse(String arg0) {                Log.i(TAG, arg0);                dealData(arg0);            }        }, new ErrorListener() {            @Override            public void onErrorResponse(VolleyError arg0) {                // TODO Auto-generated method stub            }        });        new Volley().newRequestQueue(getApplicationContext()).add(request);    }    // JSON data to java object    private void dealData(String result) {        Book book = JSON.parseObject(result, Book.class);        Log.i(TAG, book.getTitle() + "; "                + book.getPublisher() + ";"                + book.getTags().size() + ";" );    }}

 

運行結果:

08-10 21:43:11.991: I/CARLOZ(28779): {"rating":{"max":10,"numRaters":340,"average":"7.0","min":0},"subtitle":"","author":["[日] 片山恭一"],"pubdate":"2005-1","tags":[{"count":133,"name":"片山恭一","title":"片山恭一"},{"count":62,"name":"日本","title":"日本"},{"count":60,"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":"http:\/\/img3.douban.com\/mpic\/s1747553.jpg","binding":"平裝","translator":["豫人"],"catalog":"\n      ","pages":"180","images":{"small":"http:\/\/img3.douban.com\/spic\/s1747553.jpg","large":"http:\/\/img3.douban.com\/lpic\/s1747553.jpg","medium":"http:\/\/img3.douban.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元"}08-10 21:43:12.101: I/CARLOZ(28779): 滿月之夜白鯨現; 青島出版社;8;
// object to JSON data
private void dealData(String result) { List<Book> books = JSON.parseObject(result, new TypeReference<List<Book>>(){}); Book book1 = new Book(); book1.setTitle("Hello CarloZ"); Book book2 = new Book(); book2.setTitle("Hello CarloZ"); Book book3 = new Book(); book3.setTitle("Hello CarloZ"); JSON.toJSON(book1); //book1 to JSON data JSON.toJSON(books);}

 

Android JSON 解析庫的使用 - Gson 和 fast-json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.