Quantcast
Channel: Mkyong.com
Viewing all articles
Browse latest Browse all 28

How to exclude fields in Gson

$
0
0

In GSON, we can use the transient keyword, ExclusionStrategy, and @Expose to exclude fields during the JSON serialization or deserialization process.

Table of contents:

P.S Tested with Gson 2.10.1

1. Setup Google Gson

Declare gson in the pom.xml.

pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>

2. Using the “transient” Keyword

If a field is declared transient, Gson will exclude it from the serialization or deserialization process.

Person.java

package com.mkyong.json.gson.model;

public class Person {
    private int id;
    private String name;
    private transient String password;  // exclude this field

    //... getters, setters, constructors, toString and etc
}
GsonExcludeFieldExample1.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.mkyong.json.gson.model.Person;

public class GsonExcludeFieldExample1 {

    public static void main(String[] args) {

        Gson gson = new Gson();

        Person person = new Person(1, "mkyong", "password");

        String json = gson.toJson(person);

        System.out.println(json);

    }

}

Output


    {"id":1,"name":"mkyong"}

3. Using the “ExclusionStrategy”

In Gson, we can implement the ExclusionStrategy interface to control the field and define what conditions should be excluded.

The Person class now has no transient keyword for the password field.

Person.java

package com.mkyong.json.gson.model;

public class Person {
    private int id;
    private String name;
    private String password;

    //... getters, setters, constructors, toString and etc
}

Now, create a class, implement the ExclusionStrategy interface, and define the exclusion field logic within it.

The following example tells Gson to exclude the field’s name is equal to password.

PasswordExclusionStrategy.java

package com.mkyong.json.gson.exclude;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class PasswordExclusionStrategy implements ExclusionStrategy {

    // business logic to exclude field
    @Override
    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
        return "password".equalsIgnoreCase(fieldAttributes.getName());
    }

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

We need to use GsonBuilder.setExclusionStrategies to enable the above custom PasswordExclusionStrategy manually.

GsonExcludeFieldExample2.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mkyong.json.gson.exclude.PasswordExclusionStrategy;
import com.mkyong.json.gson.model.Person;

public class GsonExcludeFieldExample2 {

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();
        builder.setExclusionStrategies(new PasswordExclusionStrategy());
        Gson gson = builder.create();

        Person person = new Person(1, "mkyong", "password");

        String json = gson.toJson(person);

        System.out.println(json);

    }

}

Output


    {"id":1,"name":"mkyong"}

4. Using the “ExclusionStrategy” and custom annotation

In this example, we will create a custom annotation @GsonExcludeField to exclude fields in Gson.

A custome annotation that apply on field level.

GsonExcludeField.java

package com.mkyong.json.gson.exclude;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface GsonExcludeField {
}

Create a new ExclusionStrategy and define the logic for if @GsonExcludeField is found on the field, and Gson should exclude it during the serialization or deserialization process.

PasswordAnnotationExclusionStrategy.java

package com.mkyong.json.gson.exclude;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class PasswordAnnotationExclusionStrategy implements ExclusionStrategy {
    @Override
    public boolean shouldSkipField(FieldAttributes fieldAttributes) {

        // if found @GsonExcludeField, skip
        return fieldAttributes.getAnnotation(GsonExcludeField.class) != null;
    }

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

Put the new custom annotation @GsonExcludeField on the password field.

Person.java

package com.mkyong.json.gson.model;

import com.mkyong.json.gson.exclude.GsonExcludeField;

public class Person {
    private int id;
    private String name;

    @GsonExcludeField
    private String password;

    //... getters, setters, constructors, toString and etc
}

Run it.

GsonExcludeFieldExample3.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mkyong.json.gson.exclude.PasswordAnnotationExclusionStrategy;
import com.mkyong.json.gson.exclude.PasswordExclusionStrategy;
import com.mkyong.json.gson.model.Person;

public class GsonExcludeFieldExample3 {

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();
        builder.setExclusionStrategies(new PasswordAnnotationExclusionStrategy());
        Gson gson = builder.create();

        Person person = new Person(1, "mkyong", "password");

        String json = gson.toJson(person);

        System.out.println(json);

    }

}

Output


{"id":1,"name":"mkyong"}

5. Using the @Expose annotation

Annotate the class’s fields with @Expose.

Read the comment for self-explanatory.

Person.java

package com.mkyong.json.gson.model;

import com.google.gson.annotations.Expose;

public class Person {

    // @Expose default is @Expose(serialize = true, deserialize = true)
    @Expose
    private int id;

    // we can control exclude only during serialize or deserialize
    @Expose(serialize = true, deserialize = true)
    private String name;

    // not annotated, same as @Expose(serialize = false, deserialize = false)
    // this field will exclude if excludeFieldsWithoutExposeAnnotation() is enabled
    private String password;


    //... getters, setters, constructors, toString and etc
}

Now, enable the excludeFieldsWithoutExposeAnnotation() to tell Gson to respect the @Expose annotations.

GsonExcludeFieldExample4.java

package com.mkyong.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mkyong.json.gson.model.Person;

public class GsonExcludeFieldExample4 {

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();

        // Tells Gson object to respect @Expose annotations
        builder.excludeFieldsWithoutExposeAnnotation();

        Gson gson = builder.create();

        Person person = new Person(1, "mkyong", "password");

        String json = gson.toJson(person);

        System.out.println(json);

    }

}

Output


{"id":1,"name":"mkyong"}

6. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd gson

7. References

The post How to exclude fields in Gson appeared first on Mkyong.com.


Viewing all articles
Browse latest Browse all 28

Trending Articles