使用exclude strategy的场景:
我们知道Gson 序列化的时候通常有些字段不需要seralize到json中去,gson给我们提供了一个annotaion,Expose
定义:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Expose {
public boolean serialize() default true;
public boolean deserialize() default true;
}
可见作用域是field,生效时期是在运行时
用法:
@Expose(deserialize = true,serialize = true)
两个参数代表field支不支持序列化与反序列化
gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
根据方法名字可以得知Gson把没有被Expose字段标注的field都不会在tojson fromjson时生效,当我们tojson的使用只有很少的filed不需要序列化反序列化的时候,就需要使用expose标注很多的字段,对于程序员来说这当然是不可接受的,exclude stragety应运而生
用法:
1: 定义GsonIgnore注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GsonIgnore {
}
注意一定要是runtime,之前定义了class,在运行时并不能通过反射类方法getannotaion获取出来注解对象
2: 定义
Gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(GsonIgnore.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}).create();
流程图如下:具体的代码在excluder的exludefield中,expose注解处理也在这个类中,有兴趣可以看下
ps:之前有个同事跟我说Gson的创建时间特别长我当时天真的相信了居然毫无验证,Gson的创建很快,但如果在循环中调用会频繁创建释放对象造成内存抖动,所以可以在utils中用单例来创建Gson对象
参考:
https://juejin.im/entry/570115041ea4930055ffae57
http://blog.youkuaiyun.com/qinxiandiqi/article/details/39118351