一分鐘學會使用gson
來源:程序員人生 發布時間:2015-04-10 08:10:47 閱讀次數:3642次
Gson是1個超好用的json-對象相互轉換的工具。如果您還沒有,可以到這里去下載gson2.2.2.jar
首先準備兩個類,以下:
public class One {
int integer = 10;
String a = null;
Two comTwo = new Two();
@Override
public String toString() {
return "integer: " + integer + " ; a: " + a +" ; "+comTwo.toString() ;
}
}
public static class Two {
int twoINt;
String twoStr;
@Override
public String toString() {
// TODO Auto-generated method stub
return "twoInt: " + twoINt + " ; twoStr: " + twoStr;
}
}
new 1個One對象,將其轉換為json:
<span style="color:#006600;">Gson gson = new Gson();
One one = new One();
String oneJstr = gson.toJson(one);
System.out.println(oneJstr);</span>
結果為:
<span style="color:#006600;">{"integer":10,"comTwo":{"twoINt":0}}</span>
增加對變量a賦值:
Gson gson = new Gson();
One one = new One();
one.a = " zhang ting";
String oneJstr = gson.toJson(one);
System.out.println(oneJstr);
結果為:
<span style="color:#990000;">{"integer":10,"a":" zhang ting","comTwo":{"twoINt":0}}</span>
從json數據中構造One對象:
String js = "{"integer":10,"comTwo":{"twoInt":20}}";
One oneObj = gson.fromJson(js, One.class);
System.out.println(oneObj);
結果為:
<span style="color:#006600;">integer: 10 ; a: null ; twoInt: 0 ; twoStr: null</span>
再復雜1點,增加兩個類:
public static class OneChild extends One{
String three = "i'm three ";
List<String> list;
List<CompObj> obList;
public OneChild(){
list = new ArrayList<String>();
list.add("XXX");
list.add("ting");
obList = new ArrayList<CompObj>();
CompObj d1 = new CompObj();
d1.data="good";
CompObj d2 = new CompObj();
d2.data = "zhang";
obList.add(d1);
obList.add(d2);
}
}
public static class CompObj{
String data = " comp obj";
}
構造OneChild對象:
OneChild child = new OneChild();
String thJstr = gson.toJson(child);
System.out.println(thJstr);
輸出結果為:
<span style="color:#006600;">{"three":"iu0027m three ","list":["XXX","ting"],"obList":[{"data":"good"},{"data":"zhang"}],"integer":10,"comTwo":{"twoINt":0}}</span>
構造列表(數組):
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
target.add("gao");
target.add("zhang ting");
// Gson gson = new Gson();
String json = gson.toJson(target, listType);
System.out.println(json);
結果為:
<span style="color:#990000;">["blah","gao","zhang ting"]</span>
到此gson你就學會了,下面總結使用gson,需要注意的內容:
1、json數據中的key要和java對象中的變量名1致(辨別大小寫)
2、只有java對象有值(默許值都可以)才會轉化到json數據中。
3、java對象中的變量沒必要和json數據中的key逐一對應。
4、子類中找不到的變量會自動到父類中尋覓。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈