一个类有6个属性 ,用Gson进行序列化和反序列化,其中有1个属性须要排除。ide
方式一:经过@Expose排除 ui
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Expose { /** * If {@code true}, the field marked with this annotation is written out in the JSON while * serializing. If {@code false}, the field marked with this annotation is skipped from the * serialized output. Defaults to {@code true}. * @since 1.4 */ public boolean serialize() default true; /** * If {@code true}, the field marked with this annotation is deserialized from the JSON. * If {@code false}, the field marked with this annotation is skipped during deserialization. * Defaults to {@code true}. * @since 1.4 */ public boolean deserialize() default true; }
启用@Expose this
Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation()//只序列化和反序列化带Expose注解属性 .create();
备注:序列化字段必须添加@Expose注解,若是不添加属性将不会序列化
public class ExposeUser { public static int expStatic;//Gson默认状况会排除带有static关键字属性 @Expose public String name;//姓名 @Expose public int age;//年龄 @Expose public String sex;//性别 @Expose public int height;//身高 @Expose public float weight;//体重 public boolean isLogin;//是否登陆 @Override public String toString() { return "{\"expStatic\":\"" + expStatic + "\",\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"sex\":\"" + sex + "\",\"height\":\"" + height + "\",\"weight\":\"" + weight + "\",\"isLogin\":\"" + isLogin + "\"}"; } }
方式二:不开启注解的状况下使用transient修饰code
private transient boolean checked = true;