額~先來一句官方的話Gson是谷歌推出的解析json數(shù)據(jù)以及將對象轉(zhuǎn)換成json數(shù)據(jù)的一個開源框架. 現(xiàn)在json因其易讀性和高效率而被廣泛的使用著. 相對于java以及其它json的解析框架,Gson非常的好用.熟悉網(wǎng)絡(luò)編程的人知道,,網(wǎng)絡(luò)請求返回的數(shù)據(jù)格式一般要么是json,要么是xml,但是采用json格式這種方式是使用的最為廣泛的,。 現(xiàn)在假如網(wǎng)絡(luò)請求返回這樣一個數(shù)據(jù): 在此之前,我們需要準(zhǔn)備gson.jar 好了現(xiàn)在開始講解介紹gson了 import com.google.gson.Gson;public class Demo04 { public static void main(String[] args) { Gson gson = new Gson(); String s = gson.toJson(11111); System.out.println('(11111)->'+s); s = gson.toJson('abcdefg'); System.out.println('(abcd)->'+s); s = gson.toJson(new Long(10)); System.out.println('(10)->'+s); int[] values = { 1 ,2,3,4,5,6}; s = gson.toJson(values); System.out.println('(1 ,2,3,4,5,6)->'+s); }}
控制臺輸出: (Deserialization)反序列化操作如下: import java.util.List;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;public class Demo05 { public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new Gson(); int one = gson.fromJson('1', int.class); System.out.println('one:' + one); Integer integer = gson.fromJson('1', Integer.class); System.out.println('integer:' + integer); Long long1 = gson.fromJson('1', Long.class); System.out.println('long1:' + long1); Boolean boolean1 = gson.fromJson('false', Boolean.class); System.out.println('boolean1:' + boolean1); String str = gson.fromJson('\'abc\'', String.class); System.out.println('str:' + str); List
控制臺輸出: 2.(對象例子)Object Examples package domain;import java.util.Date;public class Student { private int id; private String name; private Date birthDay; public Student(){} public Student(int id, String name, Date birthDay) { super(); this.id = id; this.name = name; this.birthDay = birthDay; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public String toString() { return 'Student [birthDay=' + birthDay + ', id=' + id + ', name=' + name + ']'; }}
(Serialization)序列化操作如下: import com.google.gson.Gson;public class Demo03 { public static void main(String[] args) { // TODO Auto-generated method stub Weather w = new Weather('北京', '10000000001', '24', '南風(fēng)', '2級', '74%', '2', '17:45', '1', 'JC_RADAR_AZ9010_JB', '暫無實況 ', '1005'); Gson gson = new Gson(); System.out.println(gson.toJson(w)); }}
控制臺輸出(手動轉(zhuǎn)成Json格式): import com.google.gson.Gson;public class Demo03 { public static void main(String[] args) { // TODO Auto-generated method stub Weather w = new Weather('北京', '10000000001', '24', '南風(fēng)', '2級', '74%', '2', '17:45', '1', 'JC_RADAR_AZ9010_JB', '暫無實況 ', '1005'); Gson gson = new Gson(); String json = gson.toJson(w); System.out.println('json輸出:'+json); System.out.println('-----------------------------------------'); Weather w2 = gson.fromJson(json, Weather.class); System.out.println('對象輸出:'+w2); }}
控制臺輸出: json輸出(便于觀察,,轉(zhuǎn)成json格式排版):{ 'city': '北京', 'cityId': '10000000001', 'temp': '24', 'wd': '南風(fēng)', 'ws': '2級', 'sd': '74%', 'wse': '2', 'time': '17:45', 'isReader': '1', 'Radar': 'JC_RADAR_AZ9010_JB', 'njd': '暫無實況\t', 'qy': '1005'}-----------------------------------------對象輸出(便于觀察,轉(zhuǎn)成json格式排版,,實際toString):Weather[ city=北京, cityId=10000000001, temp=24, wd=南風(fēng), ws=2級, sd=74%, wse=2, time=17: 45, isReader=1, Radar=JC_RADAR_AZ9010_JB, njd=暫無實況, qy=1005]
3.現(xiàn)在來個稍微復(fù)雜一點的包含內(nèi)部類 public class Student { private int id; private String name; private Date birthDay; public Student(){} public Student(int id, String name, Date birthDay) { super(); this.id = id; this.name = name; this.birthDay = birthDay; } public String toString() { return 'Student [birthDay=' + birthDay + ', id=' + id + ', name=' + name + ']'; }}public class BoyStudent { private String sex; private String intertests; private Student student; @Override public String toString() { return 'Boy [sex=' + sex + ', intertests=' + intertests + ', student=' + student + ']'; } public Boy(String sex, String intertests, Student student) { super(); this.sex = sex; this.intertests = intertests; this.student = student; } public Boy() { }}
(Serialization)序列化,(Deserialization)反序列化操作操作如下: public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new Gson(); Student s1 = new Student(1,'s1',new Date()); BoyStudent b1 = new BoyStudent('m', '籃球', s1); String json1 = gson.toJson(b1); System.out.println('json1:'+json1); System.out.println('---------------------------'); BoyStudent bTemp = gson.fromJson(json1, BoyStudent.class); System.out.println('bTemp:'+bTemp); }
輸出: json1:{ 'sex': 'm', 'intertests': '籃球', 'student': { 'id': 1, 'name': 's1', 'birthDay': 'Mar 21, 2016 9:44:05 PM' }}---------------------------bTemp:BoyStudent[ sex=m, intertests=籃球, student=Student[ birthDay=MonMar2121: 44: 05CST2016, id=1, name=s1 ]]
4.在開發(fā)中那么這還是僅僅不夠的,,進(jìn)場返回來的json數(shù)據(jù)是一個集合,那么gson能否實現(xiàn)呢,?哈哈~那是必須的,,現(xiàn)在來個復(fù)雜一點的。 public class ResponseBoyStudent { private int errCode; private String note; private BoyStudent boyStudent; public ResponseBoyStudent(int errCode, String note, BoyStudent boyStudent) { super(); this.errCode = errCode; this.note = note; this.boyStudent = boyStudent; } @Override public String toString() { return 'ResponseBoyStudent [errCode=' + errCode + ', note=' + note + ', boyStudent=' + boyStudent + ']'; }}
(Serialization)序列化,(Deserialization)反序列化操作操作如下: public static void main(String[] args) { // TODO Auto-generated method stub Student s1 = new Student(1, 'TFboys-1', new Date()); Student s2 = new Student(2, 'TFboys-2', new Date()); Student s3 = new Student(3, 'TFboys-3', new Date()); BoyStudent b1 = new BoyStudent('M', '唱歌', s1); BoyStudent b2 = new BoyStudent('M', '跳舞', s2); BoyStudent b3 = new BoyStudent('M', '啥都不會', s3); ResponseBoyStudent rbs1 = new ResponseBoyStudent(200, 'Ok', b1); ResponseBoyStudent rbs2 = new ResponseBoyStudent(302, '跳轉(zhuǎn)', b2); ResponseBoyStudent rbs3 = new ResponseBoyStudent(404, '資源請求失敗', null); List
控制臺輸出: [ { 'errCode': 200, 'note': 'Ok', 'boyStudent': { 'sex': 'M', 'intertests': '唱歌', 'student': { 'id': 1, 'name': 'TFboys-1', 'birthDay': 'Mar 21, 2016 10:06:54 PM' } } }, { 'errCode': 302, 'note': '跳轉(zhuǎn)', 'boyStudent': { 'sex': 'M', 'intertests': '跳舞', 'student': { 'id': 2, 'name': 'TFboys-2', 'birthDay': 'Mar 21, 2016 10:06:54 PM' } } }, { 'errCode': 404, 'note': '資源請求失敗' }]--------------------------------[ ResponseBoyStudent[ errCode=200, note=Ok, boyStudent=BoyStudent[ sex=M, intertests=唱歌, student=Student[ birthDay=MonMar2122: 06: 54CST2016, id=1, name=TFboys-1 ] ] ], ResponseBoyStudent[ errCode=302, note=跳轉(zhuǎn), boyStudent=BoyStudent[ sex=M, intertests=跳舞, student=Student[ birthDay=MonMar2122: 06: 54CST2016, id=2, name=TFboys-2 ] ] ], ResponseBoyStudent[ errCode=404, note=資源請求失敗, boyStudent=null ]]
看到這里有木有想哭的趕腳,,之前寫的代碼真叫尼瑪一個累~ 我對幾個實體類稍微做了一下修改,注意觀察修改了那些內(nèi)容,,注意哪些是變化的,,哪些是沒有變化的 public class Student { private int id; private String name; private Date birthDay; /////////////////////Change///////////////////////////// public Student(){ this.id = 0; this.name = '請輸入您的姓名'; this.birthDay = new Date(); } /////////////////////Change///////////////////////////// public Student(int id, String name, Date birthDay) { super(); this.id = id; this.name = name; this.birthDay = birthDay; } public String toString() { return 'Student [birthDay=' + birthDay + ', id=' + id + ', name=' + name + ']'; }}public class BoyStudent { private String sex; private String intertests; private Student student; @Override public String toString() { return 'BoyStudent [sex=' + sex + ', intertests=' + intertests + ', student=' + student + ']'; } public BoyStudent(String sex, String intertests, Student student) { super(); this.sex = sex; this.intertests = intertests; this.student = student; } /////////////////////Change///////////////////////////// public BoyStudent() { this.sex = 'M'; this.intertests = '左手右手一個慢動作'; this.student = new Student(1000, '請輸入您的姓名', new Date()); } /////////////////////Change/////////////////////////////}public class ResponseBoyStudent { private int errCode; private String note; private BoyStudent boyStudent; public ResponseBoyStudent(int errCode, String note, BoyStudent boyStudent) { super(); this.errCode = errCode; this.note = note; this.boyStudent = boyStudent; } /////////////////////Change///////////////////////////// public ResponseBoyStudent(){ boyStudent = new BoyStudent('M','睡覺',new Student()); } ////////////////////////////////////////////////// @Override public String toString() { return 'ResponseBoyStudent [errCode=' + errCode + ', note=' + note + ', boyStudent=' + boyStudent + ']'; }}
我將用斜線表示出來改變的部分,一次是對其無參構(gòu)造函數(shù)進(jìn)行了修改,,我們來看看效果是否如我們所想那樣,。 [ { 'errCode': 200, 'note': 'Ok', 'boyStudent': { 'sex': 'M', 'intertests': '唱歌', 'student': { 'id': 1, 'name': 'TFboys-1', 'birthDay': 'Mar 21, 2016 10:41:43 PM' } } }, { 'errCode': 302, 'note': '跳轉(zhuǎn)', 'boyStudent': { 'sex': 'M', 'intertests': '跳舞', 'student': { 'id': 2, 'name': 'TFboys-2', 'birthDay': 'Mar 21, 2016 10:41:43 PM' } } }, { 'errCode': 404, 'note': '資源請求失敗' }]--------------------------------[ ResponseBoyStudent[ errCode=200, note=Ok, boyStudent=BoyStudent[ sex=M, intertests=唱歌, student=Student[ birthDay=MonMar2122: 41: 43CST2016, id=1, name=TFboys-1 ] ] ], ResponseBoyStudent[ errCode=302, note=跳轉(zhuǎn), boyStudent=BoyStudent[ sex=M, intertests=跳舞, student=Student[ birthDay=MonMar2122: 41: 43CST2016, id=2, name=TFboys-2 ] ] ], ResponseBoyStudent[ errCode=404, note=資源請求失敗, boyStudent=BoyStudent[ sex=M, intertests=睡覺, student=Student[ birthDay=MonMar2122: 41: 43CST2016, id=0, name=請輸入您的姓名 ] ] ]]
**可以發(fā)現(xiàn)json字符串未發(fā)生改變,但是反序列化的list的內(nèi)容都是部位空的,,可以推出,,json字符串中缺少鍵值的時候仍會去“調(diào)用”默認(rèn)構(gòu)造函數(shù)。 5.既然能讓空的json反序列話為不為null的實例,,那能不能返回null?不買關(guān)子了,是有的^_^. public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new GsonBuilder().serializeNulls().create(); String json = gson.toJson(null); System.out.println(json); }
控制臺輸出: null
為什么非要去Builder一個Gson實例呢,,難道直接new 出來的不可以嗎,?親測確實可以,但是這兩種方式有什么區(qū)別呢,? public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new Gson(); String json = gson.toJson(null); System.out.println(json); }
控制臺輸出: null
好,,那我么就來觀察它的區(qū)別吧! public class Foo { private final String s; private final int i; public Foo() { this(null, 5); } public Foo(String s, int i) { this.s = s; this.i = i; } @Override public String toString() { return 'Foo [s=' + s + ', i=' + i + ']'; }}
(Serialization)序列化,(Deserialization)反序列化操作操作如下: public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new Gson(); Foo foo = new Foo(); String json = gson.toJson(foo); System.out.println(json); Foo f = gson.fromJson(json, Foo.class); System.out.println('f:'+f); json = gson.toJson(null); System.out.println(json); }
控制臺輸出: {'i':5}f:Foo [s=null, i=5]null
在biu~出來的效果 public static void main(String[] args) { // TODO Auto-generated method stub Gson gson = new GsonBuilder().serializeNulls().create(); Foo foo = new Foo(); String json = gson.toJson(foo); System.out.println(json); Foo f = gson.fromJson(json, Foo.class); System.out.println('f:'+f); json = gson.toJson(null); System.out.println(json); }
控制臺輸出: {'s':null,'i':5}f:Foo [s=null, i=5]null
看出二者的區(qū)別了吧,,當(dāng)使用biu~方式時屬性為空的時候輸出來的json字符串是有鍵值key的,,而直接new出來的就沒有。 非常感謝看到這里的朋友,,最后送點一個非常實用的工具給你 工具下載地址:http://download.csdn.net/detail/u013922681/9468715 package domain;import java.lang.reflect.Field;import java.io.Serializable;import java.util.List;public class JavaName implements Serializable { public String note; public int errCode; public BoyStudent boyStudent; public class BoyStudent implements Serializable { public String sex; public String intertests; public Student student; public class Student implements Serializable { public String birthDay; public String name; public int id; public void setBirthDay(String birthDay) { this.birthDay = birthDay; } public String getBirthDay() { return this.birthDay; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setId(int id) { this.id = id; } public int getId() { return this.id; } public String toString() { String s = ''; Field[] arr = this.getClass().getFields(); for (Field f : getClass().getFields()) { try { s += f.getName() + '=' + f.get(this) + '\n,'; } catch (Exception e) { } } return getClass().getSimpleName() + '[' + (arr.length == 0 ? s : s.substring(0, s.length() - 1)) + ']'; } } public void setSex(String sex) { this.sex = sex; } public String getSex() { return this.sex; } public void setIntertests(String intertests) { this.intertests = intertests; } public String getIntertests() { return this.intertests; } public String toString() { String s = ''; Field[] arr = this.getClass().getFields(); for (Field f : getClass().getFields()) { try { s += f.getName() + '=' + f.get(this) + '\n,'; } catch (Exception e) { } } return getClass().getSimpleName() + '[' + (arr.length == 0 ? s : s.substring(0, s.length() - 1)) + ']'; } } public void setNote(String note) { this.note = note; } public String getNote() { return this.note; } public void setErrCode(int errCode) { this.errCode = errCode; } public int getErrCode() { return this.errCode; } public String toString() { String s = ''; Field[] arr = this.getClass().getFields(); for (Field f : getClass().getFields()) { try { s += f.getName() + '=' + f.get(this) + '\n,'; } catch (Exception e) { } } return getClass().getSimpleName() + '[' + (arr.length == 0 ? s : s.substring(0, s.length() - 1)) + ']'; }}
好了,,第一次寫這么認(rèn)真~覺得可以的話點個贊! |
|
來自: 昵稱35402089 > 《jsp》