您现在的位置是:首页 > 文章详情

Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例

日期:2018-04-02点击:309

Android JSON解析库Gson和Fast-json的使用对比和图书列表小案例

继上篇json解析,我用了原生的json解析,但是在有些情况下我们不得不承认,一些优秀的json解析框架确实十分的好用,今天我们为了博客的保质保量,也就不分开写,我们直接拿比较火的Gson和Fast-json来使用,末尾在进行一些分析

一.各有千秋

两大解析库的东家都是巨头,一个来自于Google官方,一个来自阿里巴巴,我们这里对他做一个简单的介绍(大多数来源于网络)

Gson

Google提供的用来java对象和JSON数据之间进行映射的JAVA类库,可以将一个JSON字符转成一个java对象,或者反过来

来看看他的优点

  • 快速,高效
  • 代码量少
  • 面向对象
  • 数据传输解析方便

Fast-json

FastJson是一个性能很好的java语言实现的Json解析器和生成器,来自阿里巴巴的工程师,具有极快的性能,超越其他的java json parser,而阿里的工程师程,fastjson是闲着全球最快的解析库

优点

  • 快速FAST(比任何一款都快)
  • 面向对象
  • 功能强大(支持普通JDK类任意java bean Class,Collection,Map,Date或者enum)
  • 零依赖(只需要有JDK即可)
  • 支持注解,全类型序列化

二.Gson的使用

Gson的使用,我们直接定义一个实体类然后进行转换

  • Gson API:https://sites.google.com/site/gson/
  • Jar下载:https://github.com/google/gson

这里我们使用到的就是Gson和Volley,所以我们需要下载好这两个架包,对了,别忘了权限

<uses-permission android:name="android.permission.INTERNET"/>

这里我们用到的接口是豆瓣的接口

  • https://api.douban.com/v2/book/1220562
{ "rating": { "max": 10, "numRaters": 351, "average": "7.0", "min": 0 }, "subtitle": "", "author": [ "[日] 片山恭一" ], "pubdate": "2005-1", "tags": [ { "count": 139, "name": "片山恭一", "title": "片山恭一" }, { "count": 66, "name": "日本", "title": "日本" }, { "count": 62, "name": "日本文学", "title": "日本文学" }, { "count": 38, "name": "小说", "title": "小说" }, { "count": 32, "name": "满月之夜白鲸现", "title": "满月之夜白鲸现" }, { "count": 15, "name": "爱情", "title": "爱情" }, { "count": 8, "name": "純愛", "title": "純愛" }, { "count": 7, "name": "外国文学", "title": "外国文学" } ], "origin_title": "", "image": "https://img3.doubanio.com/mpic/s1747553.jpg", "binding": "平装", "translator": [ "豫人" ], "catalog": "\n ", "pages": "180", "images": { "small": "https://img3.doubanio.com/spic/s1747553.jpg", "large": "https://img3.doubanio.com/lpic/s1747553.jpg", "medium": "https://img3.doubanio.com/mpic/s1747553.jpg" }, "alt": "https://book.douban.com/subject/1220562/", "id": "1220562", "publisher": "青岛出版社", "isbn10": "7543632608", "isbn13": "9787543632608", "title": "满月之夜白鲸现", "url": "https://api.douban.com/v2/book/1220562", "alt_title": "", "author_intro": "", "summary": "那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。", "price": "15.00元" }

我们分析一下这段json,实际上他很普通,就是一个数据里面一个数组,我们用Gson应该怎么去解析呢?我们先写个方法区解析这个接口得到这个Json再说吧

 /** * 解析接口 */ private void getJson() { StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { Log.i("json", s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } }); //加入volley对列 new Volley().newRequestQueue(getApplicationContext()).add(request); }

解析之后得到的json就是上面的那句了

这里写图片描述

OK。轮到我们的Gson上场了

我们要解析什么就写什么,所以定义一个Bean

package com.lgl.fastandgson.bean; import java.util.ArrayList; /** * Gson的实体类 * Created by LGL on 2016/5/21. */ public class Book { /** * 定义的变量名要和json的键值吻合 */ //书名 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; } } 

同样的,我们json里面由数组,所以需要再定义一个

package com.lgl.fastandgson.bean; /** * 标签的实体 * Created by LGL on 2016/5/21. */ 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; } } 

好了,现在我们直接解析了,一句话的事情

 /** * 解析json * * @param json */ private void Volley_json(String json) { Gson gson = new Gson(); //将json转换成实体 Book book = gson.fromJson(json, Book.class); tv_content.setText("书名:" + book.getTitle() + "\n" + "出版社:" + book.getPublisher() + "\n" + "简介:" + book.getSummary() + "\n" + "标签" + book.getTags().size() + "\n"); }

我们直接看运行点击结果

这里写图片描述

这里要注意几点

  • 1、内部嵌套的类必须是static的,要不然解析会出错;
  • 2、类里面的属性名必须跟Json字段里面的Key是一模一样的;
  • 3、内部嵌套的用[]括起来的部分是一个List,所以定义为 public List< B> b,而只用{}嵌套的就定义为 public C c,

是不是很简单,而且现在android studio上可以直接用插件生成实体类,那更加方便了

三.Fast-Json

OK,感受了Gson的强大之后,我们再来看看fastjson的奇妙之处吧;

  • Github:https://github.com/alibaba/fastjson/releases

我们需要下载架包,网上一大堆哈

前面都一样,定义两个实体类,使用Volley解析,我们重点来看一下Volley_json这个方法,这两个的用法也很像

 /** * 解析json * * @param json */ private void Volley_json(String json) { //解析 Book book = JSON.parseObject(json,Book.class); tv_content.setText("书名:" + book.getTitle() + "\n" + "出版社:" + book.getPublisher() + "\n" + "简介:" + book.getSummary() + "\n" + "标签" + book.getTags().size() + "\n"); }

只需这样,就可以解析了

这里写图片描述

但是你会说,这些都这么简单,的确,架包就是用来方便开发的,我们用一个小案例来总结这两个jar吧

四.图书列表

现在的接口,从哪里来呢,一直看博客的朋友应该知道,我喜欢去聚合数据找免费的api做演示,所以今天使用到的接口也是

这里写图片描述

APPKEY:eab1de650b181e91da30526a3e59541b

接口:http://apis.juhe.cn/goodbook/catalog?key=eab1de650b181e91da30526a3e59541b&dtype=json

得到的json

{ "resultcode": "200", "reason": "success", "result": [ { "id": "242", "catalog": "中国文学" }, { "id": "252", "catalog": "人物传记" }, { "id": "244", "catalog": "儿童文学" }, { "id": "248", "catalog": "历史" }, { "id": "257", "catalog": "哲学" }, { "id": "243", "catalog": "外国文学" }, { "id": "247", "catalog": "小说" }, { "id": "251", "catalog": "心灵鸡汤" }, { "id": "253", "catalog": "心理学" }, { "id": "250", "catalog": "成功励志" }, { "id": "249", "catalog": "教育" }, { "id": "245", "catalog": "散文" }, { "id": "256", "catalog": "理财" }, { "id": "254", "catalog": "管理" }, { "id": "246", "catalog": "经典名著" }, { "id": "255", "catalog": "经济" }, { "id": "258", "catalog": "计算机" } ], "error_code": 0 }

貌似比较简单,里面就一个数组

我们按部就班,先用volley把json解析出来

/** * 解析接口 */ private void getJson() { StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { Log.i("json", s); try { Volley_json(s); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } }); //加入volley对列 new Volley().newRequestQueue(getApplicationContext()).add(request); }

接着我们准备显示的layout,就是一个ListView,然后我们的item也就是一个TextView,这样的话,我们可以直接写实体类了

package com.lgl.fastandgson.bean; /** * 图书列表实体类 * Created by LGL on 2016/5/21. */ public class BookListBean { //ID private String id; //类型 private String catalog; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } } 

以及列表的适配器

package com.lgl.fastandgson.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.lgl.fastandgson.R; import com.lgl.fastandgson.bean.BookListBean; import java.util.List; /** * 图书列表适配器 * Created by LGL on 2016/5/21. */ public class BookListAdapter extends BaseAdapter { private Context mContext; private List<BookListBean> mList; private LayoutInflater mInflater; //构造方法 public BookListAdapter(Context mContext, List<BookListBean> mList) { this.mContext = mContext; this.mList = mList; mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if(convertView == null){ viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.list_item,null); viewHolder.mTextView = (TextView) convertView.findViewById(R.id.mTextView); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } BookListBean bean = mList.get(position); viewHolder.mTextView.setText(bean.getId()+"\n"+bean.getCatalog()); return convertView; } class ViewHolder{ private TextView mTextView; } } 

然后我们就可以解析数据开始填充了

/** * 解析json * * @param json */ private void Volley_json(String json) throws JSONException { Gson gson = new Gson(); Type listType = new TypeToken<ArrayList<BookListBean>>() { }.getType(); JSONObject object = new JSONObject(json); ArrayList<BookListBean> list = gson.fromJson(object.getString("result"), listType); adapter = new BookListAdapter(this, list); mListView.setAdapter(adapter); }

运行的结果总所周知

这里写图片描述

到这里,本篇博客就结束了,本篇博客还是十分的基础,没有牵扯太深,只是简单的介绍和使用了一下这两个框架,我们后续可能会出一些稍微高级的博客!

原文地址http://www.bieryun.com/2623.html

原文链接:https://yq.aliyun.com/articles/575008
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章