Gson序列化对象如何忽略字段

Gson版本 2.8.2

梗概

  • 用注解@Expose(serialize = false, deserialize = false)在类的成员上以告诉Gson 跳过本字段的(反)序列化
  • (反)序列化时,需要Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()而不是Gson gson = new Gson()

详情

比如有下User类,我不想把nickName也输出出来,网上说只要把注解改成@Expose(serialize = false, deserialize = false)

package test;

import com.google.gson.Gson;
import com.google.gson.annotations.Expose;

public class User {

    User(String name_, String nickName_) {
        name = name_;
        nickName = nickName_;
    }

    public static void main(String[] args) {
        User u = new User("Jackey", "Jack");
        Gson gson = new Gson();
        System.out.println(gson.toJson(u));//{"name":"Jackey","nickName":"Jack"}
    }

    @Expose
    String name;

    @Expose(serialize = false, deserialize = false)
    String nickName;
}

事实是注解改了以后, 也还是会输出nickName的。

查看了下Gson-2.8.2的源码,在Expose.java中有注释,说如何使用

public class User {
  @Expose private String firstName;
  @Expose(serialize = false) private String lastName;
  @Expose (serialize = false, deserialize = false) private String emailAddress;
  private String password;
 }

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()}
methods will use the {@code password} field along-with {@code firstName}, {@code lastName},
and {@code emailAddress} for serialization and deserialization. However, if you created Gson
with {@code Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()}
then the {@code toJson()} and {@code fromJson()} methods of Gson will exclude the
{@code password} field. This is because the {@code password} field is not marked with the
{@code @Expose} annotation. Gson will also exclude {@code lastName} and {@code emailAddress}
from serialization since {@code serialize} is set to {@code false}. Similarly, Gson will
exclude {@code emailAddress} from deserialization since {@code deserialize} is set to false.

使用Gson gson = new Gson()注解不会生效,需要用Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()去配置Gson

代码改成如下即可

package test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

public class User {

    User(String name_, String nickName_) {
        name = name_;
        nickName = nickName_;
    }

    public static void main(String[] args) {
        User u = new User("Jackey", "Jack");
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gson.toJson(u));// {"name":"Jackey"}
    }

    @Expose
    String name;

    @Expose(serialize = false, deserialize = false)
    String nickName;
}

另附gson-2.8.2下载链接

gson-2.8.2-sources.jar

gson-2.8.2.jar

posted on 2018-04-06 14:11 开学五年级了 阅读() 评论() 编辑 收藏
版权声明:本文为qwsdcv原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/qwsdcv/p/8727632.html