Gson中幾個註解類分析

在Gson 中定義了五個註解類,位於

com.google.gson.annotations 包下:
Expose,JsonAdapter,SerializedName,Since,Until五個類

Expose 類是用於註解操作某些字段序列化和反序列化過程中是否被操作

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Expose {
  
  /**
   * serialized output. Defaults to {@code true}.
   * @since 1.4
      默認true 設爲false時,被標記的字段將不會序列化 
   */
  public boolean serialize() default true;

  /**
   * Defaults to {@code true}.
   * @since 1.4
      默認true 設爲false時,被標記的字段將不會反序列化 
   */
  public boolean deserialize() default true;
}

JsonAdapter  指定當前字段使用適配器類型


public @interface JsonAdapter {
 //指定適配器,至少有一個(TypeAdapter,TypeAdapterFactory)
  /** Either a {@link TypeAdapter} or {@link TypeAdapterFactory}, or one or both of {@link JsonDeserializer} or {@link JsonSerializer}. */
  Class<?> value();

  /** false, to be able to handle {@code null} values within the adapter, default value is true. */
  boolean nullSafe() default true;

}

SerializedName  序列化名稱 具體使用請參考 Gson中SerializedName註解的使用

public @interface SerializedName {

  /**
   * @return the desired name of the field when it is serialized or deserialized
    設置一個別名,默認值
   */
  String value();
  /**
   * @return the alternative names of the field when it is deserialized
     設置多個別名字段數組
   */
  String[] alternate() default {};
}

Since  Until 類中都只有一個參數,Since代表“自從”,Until 代表”一直到”。它們都是針對該字段生效的版本。比如說 @Since(1.2)代表從版本1.2之後才生效,@Until(0.9)代表着在0.9版本之前都是生效的,它可以和上面幾個註解配合。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface Since {
  /**
   * the value indicating a version number since this member
   * or type has been present.
   */
  double value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface Until {

  /**
   * the value indicating a version number until this member
   * or type should be ignored.
   */
  double value();
}

要使用它我們必須要用GsonBuilder 來構建Gson

GsonBuilder builder = new GsonBuilder();
    builder.setVersion(1.0);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章