Google Gson 字段过滤:@Expose
程序员文章站
2024-03-16 09:27:58
...
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 + "]";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
(2) 测试代码
@Test
public 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);
}
运行测试结果:
上一篇: p-7-7辗转相除法求解最大公约数
下一篇: 贴瓷砖问题——动态规划