接着上篇SerializedName註解的使用 來看下Expise 註解的使用。
該註解只有在 你使用GsonBuilder去構造Gson時,同時調用excludeFieldsWithoutExposeAnnotation()方法 才起作用。
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;
}
該類有來過那個方法,serialize() 設置是否序列化,默認值是true,deserialize() 用於設置是否反序列化,默認值也是true,也就是說,如果我們這樣寫,該字段是無論是是序列化還是反序列化都會執行了的。
@Expose
private int age;
如果寫成這樣:
@Expose(deserialize = false,serialize = false)
private int age;
那說明該字段既不參與序列化也不參與反序列化。
看下實體類:
public class TestMode {
@Expose(deserialize = false,serialize = false)
private int age;
@Expose(serialize = false, deserialize = true)
String name;
@Expose
@SerializedName(value = "len",alternate = {"height","width"})
int length;
public TestMode() {
if (false) {
}
}
public TestMode(int age, String name, int length) {
this.age = age;
this.name = name;
this.length = length;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestMode{" +
"age=" + age +
", name='" + name + '\'' +
", length=" + length +
'}';
}
}
測試方法:
public static void main(String args[]) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.excludeFieldsWithoutExposeAnnotation();
Gson gson = gsonBuilder.create();
TestMode testMode = new TestMode(30, "明", 170);
System.out.println("序列化:" + gson.toJson(testMode));
String json = "{\"age\":30,\"name\":\"明\",\"len\":20,\"width\":80,\"height\":70}";
TestMode jsTestMode = gson.fromJson(json, TestMode.class);
System.out.println("反序列化:" + jsTestMode.toString());
}
結果:
序列化:{"len":170}
反序列化:TestMode{age=0, name='明', length=70}
要注意一點,使用GsonBuilder構建Gson,他的實體類,必須要有Expose註解,除非你不想讓該字段參加序列化和反序列化。
那我們上邊說了必須要調用excludeFieldsWithoutExposeAnnotation()方法 纔會生效,
public GsonBuilder excludeFieldsWithoutExposeAnnotation() {
//其實就是爲excluder重新負值了,那麼不調用此方法呢?
excluder = excluder.excludeFieldsWithoutExposeAnnotation();
return this;
}
private Excluder excluder = Excluder.DEFAULT;
其實他本身是有一個默認值的。
public static final Excluder DEFAULT = new Excluder();
Excluder 類沒有重寫空的的構造函數,重新給deserialize 和serialize複製,那麼他們使用的就是默認的值,都是true,所以即參加序列化,也參加反序列化。