Gson序列化字段排除

一个类有6个属性 ,用Gson进行序列化和反序列化,其中有1个属性需要排除。

方式一:通过@Expose排除  

@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 

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修饰

private transient boolean checked = true;

转载于:https://my.oschina.net/u/2485707/blog/1526045

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值