想要使用Gson,首先得导入Gson.jar,网上很多,随便搜一下就可以。
下面是Gson的一些基本的使用方法,我目前能用到的就这么多。
因为我是做Android开发的,最常使用Json的情景,就是客户端发送请求到服务器,服务器返回Json数据,客户端解析为相关的Java类对象,然后展示信息。所以,下面先演示一下用Gson根据一个类生成Json和根据Json串解析为一个类对象:
首先创建一个演示类User:
class User{
String name;
int age;
@SerializedName(value="emailAddress", alternate={"email","email_address"})
String emailAddress;
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", emailAddress=" + emailAddress + "]";
}
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public User() {
super();
}
}
接着先创建一个Gson对象:
Gson gson = new Gson();
下面就是生成json串的代码:
User user = new User("wcc", 25);
String userString = gson.toJson(user, User.class);
userString的值为:
{"name":"wcc","age":25}
接着将刚生成的Json串再解析为User对象:
// 将Json串解析成User对象
User newUser = gson.fromJson(userString, User.class);
打印出的newUser结果为:
User [name=wcc, age=25, emailAddress=null]
下面说一下注解@SerializedName的使用,它用于解决Json串的字段和相对应的类的字段不匹配的问题。
举个例子:
Json串是这样的:
String jsonString = "{\"name\":\"wcc\",\"age\":25,\"email_address\":\"bj\"}";
而相应类的字段是这样的:
String emailAddress;
如果直接解析结果为:
User [name=wcc, age=25, emailAddress=null]
在字段上加上@SerializedName注解:
@SerializedName("email_address")
tring emailAddress;
结果就变为这样了:
User [name=wcc, age=25, emailAddress=bj]
这还没完,如果Json串里有多个对象,且可能出现多个不同的email字段,如:email、email_address、emailAddress,这种情况可以用@SerializedName的alternate属性解决:
@SerializedName(value="emailAddress", alternate={"email","email_address"})
String emailAddress;
再说说通过TypeToken使用泛型,为什么要使用TypeToken呢?因为Gson是通过反射起作用的,像List<String>.class,List<Integer>.class最后得到的都是同一个字节码List.class,所以通过TypeToken可以区别不同的泛型。
下面通过解析一个Json数组说明:
String jsonArray = "['shenmu','changshengjie','zhetian']";
将上面的数组解析成一个Java数组比较简单,只要这样就行了:
String[] strArr = gson.fromJson(jsonArray, String[].class);
但是想要将其解析成List,就需要借助TypeToken:
List<String> list = gson.fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
因为TypeToken的Constructor is not visible,所以要用匿名内部类的方式调用,输出list:
[shenmu, changshengjie, zhetian]
好了,基础知识已经具备,下面来解析一个比较复杂的Json:
String jsArray = "[{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
+ "'docid': 'BUGQFHA500097U7U'}," + "{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
+ "'docid': 'BUGQFHA500097U7U'}," + "{'boardid': 'tech_bbs'," + "'clkNum': 0," + " 'digest': '',"
+ "'docid': 'BUGQFHA500097U7U'}]";
上面的Json数组具有三个内容相同的对象,不管它是什么,反正是一个对象就行了,下面将它解析成一个List,其中的每一个元素都是一个Data对象,首先看Data的定义:
class Data{
String boardid;
int clkNum;
String digest;
String docid;
@Override
public String toString() {
return "Data [boardid=" + boardid + ", clkNum=" + clkNum + ", digest=" + digest + ", docid=" + docid + "]";
}
public Data(String boardid, int clkNum, String digest, String docid) {
super();
this.boardid = boardid;
this.clkNum = clkNum;
this.digest = digest;
this.docid = docid;
}
public Data() {
}
}
上面的定义很好理解,就是声明了一些字段,下面是解析的代码:
List<Data> dl = gson.fromJson(jsArray, new TypeToken<List<Data>>(){}.getType());
一句话搞定,输出:
[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串,非常长:
static String superString = "{"
+"'V9LG4B3A0': ["
+"{"
+"'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',"
+"'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':'跟着音乐看电影'"
+"},"
+"{"
+"'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': {"
+"'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':'奇葩剧情'"
+"}]}";
上面的Json串首先是一个对象,这个对象里有一个数组,数组里又有两个子对象,子对象里又可能含对象,所以我们要定义三个相对应的Java类,首先看最里面的对象对应的类,即节点videoTopic对应的类的定义:
class VideoTopic{
String alias;
String tname;
String ename;
String tid;
@Override
public String toString() {
return "VideoTopic [alias=" + alias + ", tname=" + tname + ", ename=" + ename + ", tid=" + tid + "]";
}
}
再看数组里的对象对应的类的定义:
public class NewsBean {
String topicImg;
String videosource;
String mp4Hd_url;
String topicDesc;
String topicSid ;
String cover;
String title;
int playCount;
String replyBoard;
VideoTopic videoTopic;
String sectiontitle;
String replyid;
String description;
String mp4_url;
int length;
int playersize;
String m3u8Hd_url;
String vid;
String m3u8_url;
String ptime;
String topicName;
@Override
public String toString() {
return "NewsBean [topicImg=" + topicImg + ", videosource=" + videosource + ", mp4Hd_url=" + mp4Hd_url
+ ", topicDesc=" + topicDesc + ", topicSid=" + topicSid + ", cover=" + cover + ", title=" + title
+ ", playCount=" + playCount + ", replyBoard=" + replyBoard + ", videoTopic=" + videoTopic
+ ", sectiontitle=" + sectiontitle + ", replyid=" + replyid + ", description=" + description
+ ", mp4_url=" + mp4_url + ", length=" + length + ", playersize=" + playersize + ", m3u8Hd_url="
+ m3u8Hd_url + ", vid=" + vid + ", m3u8_url=" + m3u8_url + ", ptime=" + ptime + ", topicName="
+ topicName + "]";
}
}
看到上面的类,将VideoTopic对象作为类成员进行声明了,这样解析的时候,相关的节点videoTopic就会被解析为VideoTopic对象并作为对应的NewsBean对象的成员存在。最后看一下最外层对象所对应的类的定义:
public class Wrapper {
List<NewsBean> V9LG4B3A0;
}
因为该对象里面有一个数组,所以我把它定义为List。下面是解析的代码,很简单:
Wrapper w = gson.fromJson(superString, Wrapper.class);
遍历,并输出其中的内容:
List<NewsBean> newsList = w.V9LG4B3A0;
for(NewsBean n : newsList)
System.out.println(n+"\n");
输出结果:
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=跟着音乐看电影]
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 查看评论