Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

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