
Gson @Expose 注解可用于标记字段是否公开(包含或不包含)以进行序列化或反序列化。 @Expose 注释 可以采用两个参数,每个参数都是一个布尔值,可以采用值 true 或 false。为了让 GSON 对 @Expose 注释做出反应,我们必须使用 GsonBuilder 类创建一个 Gson 实例,并且需要调用 excludeFieldsWithoutExposeAnnotation() 方法,它将 Gson 配置为排除所有没有 Expose 注释的字段进行序列化或反序列化。
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)<strong>
</strong> 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
}以上就是如何在Java中使用@Expose注解从JSON中排除一个字段?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号