Gson解析
JSON的解析-JSONObject和JSONArray请看:http://blog.csdn.net/Peng_Hong_fu/article/details/52252986
使用Gson前,导入gson库和使用GsonFormat请看:Androidstudio导入gson
Gson的使用是依附一个Bean对象
首先建立Person的一个Bean对象
publicclassPerson{
privateStringname;
privateintage;
@Override
publicStringtoString(){
return"Person{"+
"age="+age+
",name=''"+name+''\''''+
''}'';
}
........SetterandGetter......
}
Gson使用方法
json序列化
添加json数据,将bean里面的内容转换为json内容
json序列化1
/
加入的数据是{"name":"peng","age":"19"}
一个对象
/
Personp=newPerson();
p.setName("peng");
p.setAge(19);
Gsongson=newGson();
System.out.println(gson.toJson(p));
json序列化2
/
加入的数据是[{"name":"peng","age":"19"},
{"name":"peng","age":"19"}]
数组里包含两个对象
/
Listlist=newArrayList<>();
Personp=newPerson();
p.setName("peng");
p.setAge(19);
Personq=newPerson();
q.setName("jack");
q.setAge(20);
list.add(p);
list.add(q);
Gsongson=newGson();
System.out.println(gson.toJson(list));
json序列化3
这次添加的是一个复杂的json数据,包括数组和对象的组合
这需要一个新的bean类
使用Androidstudio的GsonFormat功能可以快速的生成以下的BaoBao类
具体方法在上方的提示给出
publicclassBaoBao{
privateStringname;
privateStringage;
privateListother;
....GetterandSetter....
publicstaticclassOtherBean{
privateStringname;
privateStringage;
privateStringid;
....GetterandSetter....
}
/添加的数据是{"name":"宝强","age":"32",
"other":[{"name":"小马","age":"22","id":"1"},
{"name":"小蓉","age":"32","id":"2"},
{"name":"小王","age":"42","id":"3"}]}
/
BaoBaob=newBaoBao();
b.setName("宝强");
b.setAge("32");
Listlist=newArrayList<>();
/
如果你重写了OtherBean的构造函数
你也可以这样加数据
BaoBao.OtherBeanob=newBaoBao.OtherBean("小马","22","1");
/
BaoBao.OtherBeanob=newBaoBao.OtherBean();
ob.setName("小马");
ob.setAge("22");
ob.setId("1");
BaoBao.OtherBeanob1=newBaoBao.OtherBean();
ob1.setName("小荣");
ob1.setAge("32");
ob1.setId("2");
BaoBao.OtherBeanob2=newBaoBao.OtherBean();
ob2.setName("小王");
ob2.setAge("42");
ob2.setId("3");
list.add(ob);
list.add(ob1);
list.add(ob2);
b.setOther(list);
Gsongson=newGson();
System.out.println(gson.toJson(b));
json反序列化
json解析,从Json对象封装出一个一个的bean对象
解析1
解析{''name'':''peng'',''age'':''12''}
1
1
Stringstr="{''name'':''zhangsan'',''age'':''12''}";
Personperson=newPerson();
Gsongson=newGson();
/person=gson.fromJson("{name:''zhangsan''}",Person.class);/
person=gson.fromJson(str,Person.class);
System.out.println(person.getName()+""+person.getAge());
解析结果
解析一
解析2
二.解析[{''name'':''peng'',''age'':''23''},{''name'':''jack'',''age'':''22''}]
1
1
StringjsonData="[{''name'':''peng'',''age'':''23''},{''name'':''jack'',''age'':''22''}]";
Gsongson=newGson();
TypelistType=newTypeToken>(){}.getType();
Listlist=gson.fromJson(jsonData,listType);
//useListorLinkList
for(Personp:list){
System.out.println(p.getName()+""+p.getAge());
}
/
下面解析的方法和上面的方法有同样的效果
/
StringjsonData="[{\"name\":\"baoqiang\",\"age\":23},{\"name\":\"sunyang\",\"age\":34}]";
TypelistType=newTypeToken>(){}.getType();
Gsongson=newGson();
LinkedListlinklist=gson.fromJson(jsonData,listType);
for(Iteratoriterator=linklist.iterator();iterator.hasNext();){
Personperson=(Person)iterator.next();
System.out.println(person.getName());
System.out.println(person.getAge());
}
解析结果
解析二
解析3
这里解析一个复杂的json数据,包括数组和对象的组合
{"name":"宝强","age":"32",
"other":[{"name":"小马","age":"22","id":"1"},
{"name":"小蓉","age":"32","id":"2"},
{"name":"小王","age":"42","id":"3"}]
}
解析代码
Stringstr="{\"name\":\"宝强\",\"age\":\"32\",\n"+
"\"other\":[{\"name\":\"小马\",\"age\":\"22\",\"id\":\"1\"},\n"+
"{\"name\":\"小蓉\",\"age\":\"32\",\"id\":\"2\"},\n"+
"{\"name\":\"小王\",\"age\":\"42\",\"id\":\"3\"}]\n"+
"}";
Gsongson=newGson();
BaoBaojs=gson.fromJson(str,BaoBao.class);
System.out.println("name:"+js.getName()+"age:"+js.getAge());
Listlist=js.getOther();
for(BaoBao.OtherBeanob:list){
System.out.println("name:"+ob.getName()+"id:"+ob.getId()+"age:"+ob.getAge());
}
直接通过GsonFormat生成的bean对象提取
Gsongson=newGson();
BaoBaojs=gson.fromJson(str,BaoBao.class);
//因为定义了bean对象,可以直接通过下面的方法提取,get(0)为第一个数组
System.out.println(js.getOther().get(0).getName()+js.getOther().get(0).getAge());
//取出的结果为小马22
参考资料:
AndroidGson解析json详解
什么是JSON:
JSON即JavaScriptObjectNatation,它是一种轻量级的数据交换格式,与XML一样,是广泛被采用的客户端和服务端交互的解决方案.
JSON对象:
JSON中对象(Object)以"{"开始,以"}"结束.对象中的每一个item都是一个key-value对,表现为"key:value"的形式,key-value对之间使用逗号分隔.如:{"name":"coolxing","age"=24,"male":true,"address":{"street":"huiLongGuan","city":"beijing","country":"china"}}.JSON对象的key只能是string类型的,而value可以是string,number,false,true,null,Object对象甚至是array数组,也就是说可以存在嵌套的情况.
JSON数组:
JSON数组(array)以"["开始,以"]"结束,数组中的每一个元素可以是string,number,false,true,null,Object对象甚至是array数组,数组间的元素使用逗号分隔.如["coolxing",24,{"street":"huiLongGuan","city":"beijing","country":"china"}].
Gson的基本使用方法:
通过获取JsonReader对象解析JSON数据:
StringjsonData="[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReaderreader=newJsonReader(newStringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
StringtagName=reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
elseif(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exceptione){
e.printStackTrace();
}
通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:
创建JSON数据对应的一个POJO对象User.java:
publicclassUser{
privateStringusername;
privateintuserId;
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicintgetUserId(){
returnuserId;
}
publicvoidsetUserId(intuserId){
this.userId=userId;
}
}
使用Gson对象获取User对象数据进行相应的操作:
TypelistType=newTypeToken>(){}.getType();
Gsongson=newGson();
LinkedListusers=gson.fromJson(jsonData,listType);
for(Iteratoriterator=users.iterator();iterator.hasNext();){
Useruser=(User)www.baiyuewang.netiterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:
StringjsonData="{\"username\":\"arthinking\",\"userId\":001}";
Gsongson=newGson();
Useruser=gson.fromJson(jsonData,User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
解析复杂实例:
数据格式:
{
"data":{
"partnerteamlist":[
{
"pteamId":72825,
"ptitle":"随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",
"pteamprice":288
},
{
"pteamId":72598,
"ptitle":"随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",
"pteamprice":2888
},
{
"pteamId":72613,
"ptitle":"随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",
"pteamprice":3699
},
{
"pteamId":72638,
"ptitle":"随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",
"pteamprice":4299
},
{
"pteamId":72716,
"ptitle":"随摄影/3组服装造型/内外景拍摄/完全透明消费!",
"pteamprice":388
}
],
"liketeamlist":[
{
"lteamId":65886,
"ltitle":"爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",
"limage":"http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
"lteamprice":518,
"lmarketprice":3999
},
{
"lteamId":57133,
"ltitle":"陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",
"limage":"http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
"lteamprice":580,
"lmarketprice":3380
}
],
"feedbacks":{
"feedbacklist":[
{
"comment":"5分",
"createtime":"2014.07.0813:38",
"score":5,
"username":"l2"
}
],
"totalcount":1,
"totalscore":5
}
},
"err":null,
"state":1
}
实体类(里面的成员变量和接口的返回值名称一一对应才能保证解析正确):
packagecom.pztuan.entity;
importjava.util.List;
publicclassOtherDetail{
privateintstate;
privateListerr;
privateOtherDetail2data;
publicintgetState(){
returnstate;
}
publicvoidsetState(intstate){
this.state=state;
}
publicListgetErr(){
returnerr;
}
publicvoidsetErr(Listerr){
this.err=err;
}
publicOtherDetail2getData(){
returndata;
}
publicvoidsetData(OtherDetail2data){
this.data=data;
}
publicclassOtherDetail2{
privateListpartnerteamlist;
privateListliketeamlist;
privateListfeedbacks;
publicListgetLiketeamlist(){
returnliketeamlist;
}
publicvoidsetLiketeamlist(Listliketeamlist){
this.liketeamlist=liketeamlist;
}
publicListgetFeedbacks(){
returnfeedbacks;
}
publicvoidsetFeedbacks(Listfeedbacks){
this.feedbacks=feedbacks;
}
publicclasspartnerteamlist{
privateintpteamId;
privateStringptitle;
privateDoublepteamprice;
publicintgetPteamId(){
returnpteamId;
}
publicvoidsetPteamId(intpteamId){
this.pteamId=pteamId;
}
publicStringgetPtitle(){
returnptitle;
}
publicvoidsetPtitle(Stringptitle){
this.ptitle=ptitle;
}
publicDoublegetPteamprice(){
returnpteamprice;
}
publicvoidsetPteamprice(Doublepteamprice){
this.pteamprice=pteamprice;
}
}
publicclassliketeamlist{
privateintlteamId;
privateStringltitle;
privateStringlimage;
privateDoublelteamprice;
privateDoublelmarketprice;
publicintgetLteamId(){
returnlteamId;
}
publicvoidsetLteamId(intlteamId){
this.lteamId=lteamId;
}
publicStringgetLtitle(){
returnltitle;
}
publicvoidsetLtitle(Stringltitle){
this.ltitle=ltitle;
}
publicStringgetLimage(){
returnlimage;
}
publicvoidsetLimage(Stringlimage){
this.limage=limage;
}
publicDoublegetLteamprice(){
returnlteamprice;
}
publicvoidsetLteamprice(Doublelteamprice){
this.lteamprice=lteamprice;
}
publicDoublegetLmarketprice(){
returnlmarketprice;
}
publicvoidsetLmarketprice(Doublelmarketprice){
this.lmarketprice=lmarketprice;
}
}
publicclassfeedbacks{
privateinttotalcount;
privateDoubletotalscore;
privateListfeedbacklist;
publicintgetTotalcount(){
returntotalcount;
}
publicvoidsetTotalcount(inttotalcount){
this.totalcount=totalcount;
}
publicDoublegetTotalscore(){
returntotalscore;
}
publicvoidsetTotalscore(Doubletotalscore){
this.totalscore=totalscore;
}
publicListgetFeedbacklist(){
returnfeedbacklist;
}
publicvoidsetFeedbacklist(Listfeedbacklist){
this.feedbacklist=feedbacklist;
}
publicclassfeedbacklist{
privateStringusername;
privateStringcomment;
privateStringcreatetime;
privateDoublescore;
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetComment(){
returncomment;
}
publicvoidsetComment(Stringcomment){
this.comment=comment;
}
publicStringgetCreatetime(){
returncreatetime;
}
publicvoidsetCreatetime(Stringcreatetime){
this.createtime=createtime;
}
publicDoublegetScore(){
returnscore;
}
publicvoidsetScore(Doublescore){
this.score=score;
}
}
}
publicListgetPartnerteamlist(){
returnpartnerteamlist;
}
publicvoidsetPartnerteamlist(Listpartnerteamlist){
this.partnerteamlist=partnerteamlist;
}
}
publicclasserr{
privateintcode;
privateStringmsg;
publicintgetCode(){
returncode;
}
publicvoidsetCode(intcode){
this.code=code;
}
publicStringgetMsg(){
returnmsg;
}
publicvoidsetMsg(Stringmsg){
this.msg=msg;
}
}
}
注意上面内部类的运用。
解析:
Gsongson=newGson();
OtherDetaild=gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)
|
|