Google Gson 字段过滤:@Expose
来源:互联网 发布:英文发音软件 编辑:程序博客网 时间:2024/05/17 23:21
本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。
Google Gson 使用 @Expose 注解实现字段过滤,该注解必须和 com.google.gson.GsonBuilder 类配合使用,如果使用 com.google.gson.Gson 类则不会产生任何作用。
(1) @Expose(serialize = true, deserialize = true):序列化和反序列化时都生效,即序列化和反序列化都会处理
(2) @Expose(serialize = false, deserialize = false):序列化和反序列化时都不生效,即序列化和反序列化都忽略,和不加 @Expose 注解效果一样
(3) @Expose(serialize = true, deserialize = false):只有序列化时生效,即序列化时处理,反序列化时忽略
(4) @Expose(serialize = false, deserialize = true):只有反序列化时生效,即反序列化时处理,序列化时忽略
示例
(1) POJO 类
public class User { @Expose(serialize = true, deserialize = true) private String account; @Expose(serialize = false, deserialize = false) private String password; @Expose(serialize = true, deserialize = false) private String name; @Expose(serialize = false, deserialize = true) private int age; public User() {} public User(String account, String password, String name, int age) { this.account = account; this.password = password; this.name = name; this.age = age; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + "]"; }}
(2) 测试代码
@Testpublic void test() throws IOException { Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); User user = new User("admin", "123456", "John", 30); System.out.println(gson.toJson(user)); String userStr = "{\"account\":\"normal\",\"password\":\"xyz123\",\"name\":\"Normal\",\"age\":25}"; User normalUser = gson.fromJson(userStr, User.class); System.out.println(normalUser);}
运行测试结果:
0 0
- Google Gson 字段过滤:@Expose
- Google Gson 字段过滤:基于 Gson 版本
- Google Gson 字段过滤:自定义过滤规则
- Google Gson 字段过滤:基于访问修饰符
- Gson 字段过滤
- Gson Builder — 如何使用 @Expose 忽略字段
- 安卓注解使用,实体类指定须使用字段, Google Gson 字段过滤
- 【完美解决系列】duplicate entry: com/google/gson/annotations/Expose.class
- Gson 过滤字段的几种方法
- Gson 过滤字段的几种方法
- Gson 过滤字段的几种方法
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- gson的@Expose注解和@SerializedName注解
- 用CSS将div变成三角形
- PROTEL 99 常用库文件&分立元件库和快捷键
- Android仿小米商城底部导航栏(基于BottomNavigationBar)
- Spring学习(3)
- android WebView 讲解
- Google Gson 字段过滤:@Expose
- 柯朗微积分与数学分析习题选解(1.3 节 c)
- 第一篇博客
- 多种设计模式,需要掌握熟练的有哪些
- openjudge.1.8.22 神奇的幻方
- Android通用网络请求解析框架.3(代码实现,公共部分)
- jquery 日期比较 以及日期校验
- Android studio cMake 使用详解
- bootstrap导航栏、下拉菜单、表单的简单应用