如何使用 Java 中的 @Expose 注解从 JSON 中排除一个字段?
Gson @Expose 注解可用于标记一个字段是否公开或不公开(包含或不包含)以序列化或反序列化。@Expose 注解可以接受两个参数,每个参数都是一个布尔值,可以取值 true 或 false。为让 GSON 对 @Expose 注解做出响应,我们必须使用 GsonBuilder 类创建一个 Gson 实例,并需要调用 excludeFieldsWithoutExposeAnnotation() 方法进行配置从对没有 Expose 注解的序列化或反序列化进行考虑的所有字段中排除 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);
}
}
// Employee class
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
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP