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
}