Gson序列化字段排除

一個類有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;
相關文章
相關標籤/搜索