ignore field when serialize/deserialize with Gson

While we use Gson for serializing/deserializing, some field we might want to ignore.

A direct way is to make the field transient.

Alternatively we could use the @Expose to annotate the field we want to be handled. However there is currently no way to ignore in one way. Here is a solution

 /**
         *  we can exclude a few fields with @Expose(serialize = false) or @Expose(deserialize = false) annotations (note that the default value for
         *  both @Expose attributes is true). You can of course use @Expose(serialize = false, deserialize = false), but that is more concisely accomplished
         *  by declaring the field transient instead (which does still take effect with these custom exclusion strategies).
         */
        GsonBuilder gsonBuilder = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy()
        {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes)
            {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.serialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass)
            {
                return false;
            }
        }).addDeserializationExclusionStrategy(new ExclusionStrategy()
        {
            @Override
            public boolean shouldSkipField(FieldAttributes fieldAttributes)
            {
                final Expose expose = fieldAttributes.getAnnotation(Expose.class);
                return expose != null && !expose.deserialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> aClass)
            {
                return false;
            }
        });

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s