分享一个Gson的APT版本开源库给大家
这个库的使用方法和原生的Gson的使用方式基本一样,但是因为使用了APT(Annotation Processing Tool)而使解析效率得到了提高
GsonAPT库的地址
使用方法:
1 导入库
这个库是开源的: 建议直接拷贝:gsonaptannotation和gsonaptcomplier两个module进入自己工程。
接着:
dependencies {
...
compile project(':gsonaptannotation')
apt project(':gsonaptcomplier')
}
2 添加@Jsonbean到自己希望解析的相关类上
@JsonBean
public class LittleBean {
String littleBeanName;
public String getLittleBeanName() {
return littleBeanName;
}
public void setLittleBeanName(String littleBeanName) {
this.littleBeanName = littleBeanName;
}
public LittleBean() {
}
public LittleBean(String littleBeanName) {
this.littleBeanName = littleBeanName;
}
}
3 编译工程
编译后会生成GsonAPT类
4 使用GsonAPT代替new Gson()
TestBean testBean = new TestBean();
String str = GsonAPT.toJson(testBean);
testBean = GsonAPT.fromJson(str,TestBean.class);
Map<Integer, OtherBean> map = new HashMap<>();
map.put(9, new OtherBean(""));
map.put(1, new OtherBean(null));
String mapStr = GsonAPT.toJson(map);
map = GsonAPT.fromJson(mapStr,new TypeToken<Map<Integer, OtherBean>>() {
}.getType());
引用测试结果
How fast
how much time to parse the small bean:
times | Gson toJson | GsonAPT toJson | Gson fromJson | GsonAPT fromJson |
---|---|---|---|---|
10 | 3 | 1 | 10 | 1 |
10000 | 738 | 363 | 883 | 756 |
100000 | 8361 | 4420 | 10616 | 9346 |
how much time to parse the big bean:
times | Gson toJson | GsonAPT toJson | Gson fromJson | GsonAPT fromJson |
---|---|---|---|---|
1 | 673 | 325 | 811 | 700 |
10 | 7748 | 3740 | 9506 | 8182 |
times | Gson toJson Speed / GsonAPT toJson Speed |
---|---|
10000(small) | 49% |
100000(small) | 52% |
1(big) | 48% |
10(big) | 48% |
times | Gson fromJson Speed / GsonAPT fromJson Speed |
---|---|
10000(small) | 86% |
100000(small) | 88% |
1(big) | 86% |
10(big) | 86% |
注意点
@JsonBean的相关类的字段需要有get/set方法或者是 public或包访问的
和默认的Gson一样,不能解析非静态的内部类
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。