Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Gson的基础用法

$
0
0
想要使用Gson,首先得导入Gson.jar,网上很多,随便搜一下就可以。
下面是Gson的一些基本的使用方法,我目前能用到的就这么多。
因为我是做Android开发的,最常使用Json的情景,就是客户端发送请求到服务器,服务器返回Json数据,客户端解析为相关的Java类对象,然后展示信息。所以,下面先演示一下用Gson根据一个类生成Json和根据Json串解析为一个类对象:
首先创建一个演示类User:
  1. class User{
  2. String name;
  3. int age;
  4. @SerializedName(value="emailAddress", alternate={"email","email_address"})
  5. String emailAddress;
  6. @Override
  7. public String toString() {
  8. return "User [name=" + name + ", age=" + age + ", emailAddress=" + emailAddress + "]";
  9. }
  10. public User(String name, int age) {
  11. super();
  12. this.name = name;
  13. this.age = age;
  14. }
  15. public User() {
  16. super();
  17. }
  18. }
接着先创建一个Gson对象:
  1. Gson gson = new Gson();
下面就是生成json串的代码:
  1. User user = new User("wcc", 25);
  2. String userString = gson.toJson(user, User.class);
userString的值为:
  1. {"name":"wcc","age":25}
接着将刚生成的Json串再解析为User对象:
  1. // 将Json串解析成User对象
  2. User newUser = gson.fromJson(userString, User.class);
打印出的newUser结果为:
  1. User [name=wcc, age=25, emailAddress=null]

下面说一下注解@SerializedName的使用,它用于解决Json串的字段和相对应的类的字段不匹配的问题。
举个例子:
Json串是这样的:
  1. String jsonString = "{\"name\":\"wcc\",\"age\":25,\"email_address\":\"bj\"}";
而相应类的字段是这样的:
  1. String emailAddress;
如果直接解析结果为:
  1. User [name=wcc, age=25, emailAddress=null]
在字段上加上@SerializedName注解:
  1. @SerializedName("email_address")
  2. tring emailAddress;
结果就变为这样了:
  1. User [name=wcc, age=25, emailAddress=bj]
这还没完,如果Json串里有多个对象,且可能出现多个不同的email字段,如:email、email_address、emailAddress,这种情况可以用@SerializedName的alternate属性解决:
  1. @SerializedName(value="emailAddress", alternate={"email","email_address"})
  2. String emailAddress;

再说说通过TypeToken使用泛型,为什么要使用TypeToken呢?因为Gson是通过反射起作用的,像List<String>.class,List<Integer>.class最后得到的都是同一个字节码List.class,所以通过TypeToken可以区别不同的泛型。
下面通过解析一个Json数组说明:
  1. String jsonArray = "['shenmu','changshengjie','zhetian']";
将上面的数组解析成一个Java数组比较简单,只要这样就行了:
  1. String[] strArr = gson.fromJson(jsonArray, String[].class);
但是想要将其解析成List,就需要借助TypeToken:
  1. List<String> list = gson.fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
因为TypeToken的Constructor is not visible,所以要用匿名内部类的方式调用,输出list:
  1. [shenmu, changshengjie, zhetian]

好了,基础知识已经具备,下面来解析一个比较复杂的Json:
  1. String jsArray = "[{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
  2. + "'docid': 'BUGQFHA500097U7U'}," + "{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
  3. + "'docid': 'BUGQFHA500097U7U'}," + "{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
  4. + "'docid': 'BUGQFHA500097U7U'}]";
上面的Json数组具有三个内容相同的对象,不管它是什么,反正是一个对象就行了,下面将它解析成一个List,其中的每一个元素都是一个Data对象,首先看Data的定义:
  1. class Data{
  2. String boardid;
  3. int clkNum;
  4. String digest;
  5. String docid;
  6. @Override
  7. public String toString() {
  8. return "Data [boardid=" + boardid + ", clkNum=" + clkNum + ", digest=" + digest + ", docid=" + docid + "]";
  9. }
  10. public Data(String boardid, int clkNum, String digest, String docid) {
  11. super();
  12. this.boardid = boardid;
  13. this.clkNum = clkNum;
  14. this.digest = digest;
  15. this.docid = docid;
  16. }
  17. public Data() {
  18. }
  19. }
上面的定义很好理解,就是声明了一些字段,下面是解析的代码:
  1. List<Data> dl = gson.fromJson(jsArray, new TypeToken<List<Data>>(){}.getType());
一句话搞定,输出:
  1. [Data [boardid=tech_bbs, clkNum=0, digest=, docid=BUGQFHA500097U7U], Data [boardid=tech_bbs, clkNum=0, digest=, docid=BUGQFHA500097U7U], Data [boardid=tech_bbs, clkNum=0, digest=, docid=BUGQFHA500097U7U]]


最后解析一个对我来说很复杂的Json串,非常长:
  1. static String superString = "{"
  2. +"'V9LG4B3A0': ["
  3. +"{"
  4. +"'topicImg':'http://vimg3.ws.126.net/image/snapshot/2016/8/O/N/VBSN1KMON.jpg',"
  5. +"'videosource':'新媒体',"
  6. +"'mp4Hd_url':'http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/HD/jDXFt0488-mobile.mp4',"
  7. +"'topicDesc':'好的音乐铸就好的电影,不定期将为大家推荐各类经典影片,一起跟着音乐看电影吧!',"
  8. +"'topicSid':'VBSN1KMOH',"
  9. +"'cover':'http://vimg2.ws.126.net/image/snapshot/2016/8/0/2/VBTJGJQ02.jpg',"
  10. +"'title':'「跟着音乐看电影」第四期:爆裂鼓手',"
  11. +"'playCount': 11575,"
  12. +"'replyBoard':'video_bbs',"
  13. +"'sectiontitle':'',"
  14. +"'replyid':'BTJGJQ01008535RB',"
  15. +"'description':'本期推荐的是2014年上映的剧情音乐电影《爆裂鼓手》,推荐音乐Caravan。',"
  16. +"'mp4_url':'http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/SD/jDXFt0488-mobile.mp4',"
  17. +"'length': 304,"
  18. +"'playersize': 0,"
  19. +"'m3u8Hd_url':'http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/HD/movie_index.m3u8',"
  20. +"'vid':'VBTJGJQ01',"
  21. +"'m3u8_url':'http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/SD/movie_index.m3u8',"
  22. +"'ptime':'2016-08-15 17:20:25',"
  23. +"'topicName':'跟着音乐看电影'"
  24. +"},"
  25. +"{"
  26. +"'topicImg':'http://vimg1.ws.126.net/image/snapshot/2016/3/U/K/VBI02N0UK.jpg',"
  27. +"'videosource':'新媒体',"
  28. +"'mp4Hd_url':'http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/HD/aObgM2410-mobile.mp4',"
  29. +"'topicDesc':'奇葩事的大盘点。',"
  30. +"'topicSid':'VBI02N0UI',"
  31. +"'cover':'http://vimg1.ws.126.net/image/snapshot/2016/8/7/U/VBTJIF17U.jpg',"
  32. +"'title':'快放假拉横幅了多少时间',"
  33. +"'playCount': 5113,"
  34. +"'replyBoard':'video_bbs',"
  35. +"'videoTopic': {"
  36. +"'alias':'奇葩事的大盘点。',"
  37. +"'tname':'奇葩剧情',"
  38. +"'ename':'T1460515713166',"
  39. +"'tid':'T1460515713166'"
  40. +"},"
  41. +"'sectiontitle':'',"
  42. +"'replyid':'BTJIBJNG008535RB',"
  43. +"'description':'快放假拉横幅了多少时间',"
  44. +"'mp4_url':'http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/SD/aObgM2410-mobile.mp4',"
  45. +"'length': 120,"
  46. +"'playersize': 1,"
  47. +"'m3u8Hd_url':'http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/HD/movie_index.m3u8',"
  48. +"'vid':'VBTJIBJNG',"
  49. +"'m3u8_url':'http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/SD/movie_index.m3u8',"
  50. +"'ptime':'2016-08-15 17:13:44',"
  51. +"'topicName':'奇葩剧情'"
  52. +"}]}";
上面的Json串首先是一个对象,这个对象里有一个数组,数组里又有两个子对象,子对象里又可能含对象,所以我们要定义三个相对应的Java类,首先看最里面的对象对应的类,即节点videoTopic对应的类的定义:
  1. class VideoTopic{
  2. String alias;
  3. String tname;
  4. String ename;
  5. String tid;
  6. @Override
  7. public String toString() {
  8. return "VideoTopic [alias=" + alias + ", tname=" + tname + ", ename=" + ename + ", tid=" + tid + "]";
  9. }
  10. }
再看数组里的对象对应的类的定义:
  1. public class NewsBean {
  2. String topicImg;
  3. String videosource;
  4. String mp4Hd_url;
  5. String topicDesc;
  6. String topicSid ;
  7. String cover;
  8. String title;
  9. int playCount;
  10. String replyBoard;
  11. VideoTopic videoTopic;
  12. String sectiontitle;
  13. String replyid;
  14. String description;
  15. String mp4_url;
  16. int length;
  17. int playersize;
  18. String m3u8Hd_url;
  19. String vid;
  20. String m3u8_url;
  21. String ptime;
  22. String topicName;
  23. @Override
  24. public String toString() {
  25. return "NewsBean [topicImg=" + topicImg + ", videosource=" + videosource + ", mp4Hd_url=" + mp4Hd_url
  26. + ", topicDesc=" + topicDesc + ", topicSid=" + topicSid + ", cover=" + cover + ", title=" + title
  27. + ", playCount=" + playCount + ", replyBoard=" + replyBoard + ", videoTopic=" + videoTopic
  28. + ", sectiontitle=" + sectiontitle + ", replyid=" + replyid + ", description=" + description
  29. + ", mp4_url=" + mp4_url + ", length=" + length + ", playersize=" + playersize + ", m3u8Hd_url="
  30. + m3u8Hd_url + ", vid=" + vid + ", m3u8_url=" + m3u8_url + ", ptime=" + ptime + ", topicName="
  31. + topicName + "]";
  32. }
  33. }
看到上面的类,将VideoTopic对象作为类成员进行声明了,这样解析的时候,相关的节点videoTopic就会被解析为VideoTopic对象并作为对应的NewsBean对象的成员存在。最后看一下最外层对象所对应的类的定义:
  1. public class Wrapper {
  2. List<NewsBean> V9LG4B3A0;
  3. }
因为该对象里面有一个数组,所以我把它定义为List。下面是解析的代码,很简单:
  1. Wrapper w = gson.fromJson(superString, Wrapper.class);
遍历,并输出其中的内容:
  1. List<NewsBean> newsList = w.V9LG4B3A0;
  2. for(NewsBean n : newsList)
  3. System.out.println(n+"\n");
输出结果:
  1. NewsBean [topicImg=http://vimg3.ws.126.net/image/snapshot/2016/8/O/N/VBSN1KMON.jpg, videosource=新媒体, mp4Hd_url=http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/HD/jDXFt0488-mobile.mp4, topicDesc=好的音乐铸就好的电影,不定期将为大家推荐各类经典影片,一起跟着音乐看电影吧!, topicSid=VBSN1KMOH, cover=http://vimg2.ws.126.net/image/snapshot/2016/8/0/2/VBTJGJQ02.jpg, title=「跟着音乐看电影」第四期:爆裂鼓手, playCount=11575, replyBoard=video_bbs, videoTopic=null, sectiontitle=, replyid=BTJGJQ01008535RB, description=本期推荐的是2014年上映的剧情音乐电影《爆裂鼓手》,推荐音乐Caravan。, mp4_url=http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/SD/jDXFt0488-mobile.mp4, length=304, playersize=0, m3u8Hd_url=http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/HD/movie_index.m3u8, vid=VBTJGJQ01, m3u8_url=http://flv2.bn.netease.com/videolib3/1608/15/jDXFt0488/SD/movie_index.m3u8, ptime=2016-08-15 17:20:25, topicName=跟着音乐看电影]
  2. NewsBean [topicImg=http://vimg1.ws.126.net/image/snapshot/2016/3/U/K/VBI02N0UK.jpg, videosource=新媒体, mp4Hd_url=http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/HD/aObgM2410-mobile.mp4, topicDesc=奇葩事的大盘点。, topicSid=VBI02N0UI, cover=http://vimg1.ws.126.net/image/snapshot/2016/8/7/U/VBTJIF17U.jpg, title=快放假拉横幅了多少时间, playCount=5113, replyBoard=video_bbs, videoTopic=VideoTopic [alias=奇葩事的大盘点。, tname=奇葩剧情, ename=T1460515713166, tid=T1460515713166], sectiontitle=, replyid=BTJIBJNG008535RB, description=快放假拉横幅了多少时间, mp4_url=http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/SD/aObgM2410-mobile.mp4, length=120, playersize=1, m3u8Hd_url=http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/HD/movie_index.m3u8, vid=VBTJIBJNG, m3u8_url=http://flv2.bn.netease.com/videolib3/1608/15/aObgM2410/SD/movie_index.m3u8, ptime=2016-08-15 17:13:44, topicName=奇葩剧情]


最后,想要更深入的了解Gson的用法,可以去http://www.jianshu.com/p/e740196225a4看看,我在这里只是梳理一下自己所学。
作者:miyuexingchen 发表于2016/8/16 17:34:47 原文链接
阅读:13 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles