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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章