一分钟学会使用gson
来源:程序员人生 发布时间:2015-04-10 08:10:47 阅读次数:3514次
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、子类中找不到的变量会自动到父类中寻觅。
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠