Skip to content

Instantly share code, notes, and snippets.

@JeasonWong
Last active August 23, 2017 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeasonWong/e0e6912ed3b1a8d058fdc0651f42642c to your computer and use it in GitHub Desktop.
Save JeasonWong/e0e6912ed3b1a8d058fdc0651f42642c to your computer and use it in GitHub Desktop.

gson解析时可以指定某个变量是否参与序列化与反序列化

比如:

    main(){
        String str = "{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}";
        Custom custom = gson.fromJson(str, Custom.class);
        Log.d("@=>", custom.toString());
    }

    public static class Custom {
        private int a;
        transient private int b; //方式1
        @Expose private int c;  //方式2

        @Override
        public String toString() {
            return "Custom{" +
                    "a=" + a +
                    ", b=" + b +
                    ", c=" + c +
                    '}';
        }
    }

方式1是可行的,输出的结果是 @=>: Custom{a=1, b=0, c=3} ,那么方式2什么时候有效呢?

想让@Expose有效的话,gson得这样初始化:

        GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation();
        Gson gson = builder.create();

excludeFieldsWithoutExposeAnnotation 方法如其名,没有@Expose注解的变量将会被排除在外,什么意思?

刚刚的Custom中的a,b,c,没有@Expose的变量都不会被序列化和反序列化,@Expose可以自己选择性的是否需要序列化和反序列化,比如:

        private int a;
        transient private int b;
        @Expose(serialize = true, deserialize = false) private int c;

这样的话,只有c会被序列化,a、b都不会被序列化和反序列化。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment