Gson @Expose批注可用于標記要公開或不公開(串行化或反序列化)的字段。 @expose注釋可以取兩個參數和每個參數是可以采取任一值的布爾真或假。為了使GSON對@Expose批注做出反應,我們必須使用GsonBuilder類創建一個Gson實例,并需要調用excludeFieldsWithoutExposeAnnotation()方法,它將Gson配置為從所有考慮不包含序列號或反序列化的字段中排除所有字段公開注釋。
語法public?GsonBuilder?excludeFieldsWithoutExposeAnnotation()
示例import?com.google.gson.*;
import?com.google.gson.annotations.*;
public?class?JsonExcludeAnnotationTest?{
public?static?void?main(String?args[])?{
Employee?emp?=?new?Employee("Raja",?28,?40000.00);
Gson?gson?=?new?GsonBuilder().setPrettyPrinting().create();
String?jsonStr?=?gson.toJson(emp);
System.out.println(jsonStr);
gson?=?new?GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
jsonStr?=?gson.toJson(emp);
System.out.println(jsonStr);
}
}
//員工階層
class?Employee?{
@Expose(serialize?=?true,?deserialize?=?true)
public?String?name;
@Expose(serialize?=?true,?deserialize?=?true)
public?int?age;
@Expose(serialize?=?false,?deserialize?=?false)???public?double?salary;
public?Employee(String?name,?int?age,?double?salary)?{
this.name?=?name;
this.age?=?age;
this.salary?=?salary;
}
}
輸出結果{
"name":?"Raja",
"age":?28,
"salary":?40000.0
}
{
"name":?"Raja",
"age":?28
}