Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

List the ways to exclude a field from Gson serialization and say when you would use each.

Gson offers five ways to keep a field out of the JSON: mark it transient, which is skipped by default; switch to an allow-list with @Expose and excludeFieldsWithoutExposeAnnotation(), where the serialize and deserialize flags control each direction; write an ExclusionStrategy with shouldSkipField and shouldSkipClass for rules such as a custom @Internal annotation; apply a strategy in only one direction with addSerializationExclusionStrategy or addDeserializationExclusionStrategy; and change which modifiers are skipped with excludeFieldsWithModifiers, which by default means static and transient.

Why this question is asked

Every API eventually has fields that must not travel: secrets, internal flags, caches, back-references that would create loops. Gson serializes every field by default, so hiding one is a decision we make explicitly, and each mechanism has a different scope and different side effects. Interviewers ask this to see whether we know more than transient, and whether we can pick the right tool for a one-off field, a whole class of fields, or a security rule. In this answer, we will start from a class with fields to hide, go through each mechanism with its output, and finish with a comparison of when to use which.

1The Example Class

We will use one class throughout. By default, Gson writes every non-static, non-transient field, private or not.

Java
public class Account {
private long id = 7;
private String email = "ana@example.com";
private String passwordHash = "$2a$10$...";
private boolean fraudFlag = true; // internal
private Map<String, Object> cache = Map.of(); // derived data
}
System.out.println(new Gson().toJson(new Account()));
// {"id":7,"email":"ana@example.com","passwordHash":"$2a$10$...","fraudFlag":true,"cache":{}}

We want to hide cache because it is derived, passwordHash because it is secret, and fraudFlag because it is internal. Each of those is a slightly different kind of rule, and that is why Gson has more than one mechanism.

2Way 1: Mark the Field transient

transient is a Java keyword meaning "not part of the persistent state of this object". Gson honours it: by default, it skips static and transient fields.

Java
private transient Map<String, Object> cache = Map.of();
// {"id":7,"email":"ana@example.com","passwordHash":"$2a$10$...","fraudFlag":true}

This is the quickest option and right for genuinely derived data. But there is a catch: transient is not a Gson annotation, it is a language keyword that other tools also read. Java serialization skips it, and JPA treats a transient field as not persistent, so putting transient on an entity's passwordHash would stop it being saved to the database. Use transient only when the field really is transient everywhere.

3Way 2: An Allow-List With @Expose

With excludeFieldsWithoutExposeAnnotation(), Gson flips its default: only fields annotated with @Expose are included. The annotation's serialize and deserialize flags, both true by default, control each direction.

Java
public class Account {
@Expose private long id = 7;
@Expose private String email = "ana@example.com";
@Expose(serialize = false, deserialize = true) private String password; // accepted, never written
private String passwordHash = "$2a$10$..."; // not exposed: never written or read
private boolean fraudFlag = true; // not exposed
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(account)); // {"id":7,"email":"ana@example.com"}

This is an allow-list: a field nobody thought about is hidden by default. That makes it the safest choice for objects that cross a trust boundary, because adding a new sensitive field later cannot leak it by accident. The cost is that every included field needs an annotation, and the rule only works if every Gson instance uses the builder setting; a plain new Gson() ignores @Expose completely.

4Way 3: An ExclusionStrategy for Custom Rules

An ExclusionStrategy is a small interface with two methods. shouldSkipField(FieldAttributes f) is asked about each field, and FieldAttributes gives its name, declared type, declaring class and annotations. shouldSkipClass(Class<?> c) is asked about each type, and returning true hides every field of that type. This is how we express rules like "never serialize anything marked @Internal".

Java
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD)
public @interface Internal { }
ExclusionStrategy internal = new ExclusionStrategy() {
@Override public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Internal.class) != null;
}
@Override public boolean shouldSkipClass(Class<?> c) {
return c == SecretKey.class; // never serialize keys, wherever they appear
}
};
Gson gson = new GsonBuilder().setExclusionStrategies(internal).create();
// with @Internal on fraudFlag:
// {"id":7,"email":"ana@example.com","passwordHash":"$2a$10$..."}

The annotation must have RUNTIME retention, otherwise it is not visible by reflection and the strategy never sees it. A strategy is the right tool when the rule belongs to the company rather than to one class, because it lives in the shared Gson configuration.

5Way 4 and 5: One Direction Only, and Changing Modifiers

setExclusionStrategies applies a strategy to both writing and reading. Sometimes we want only one: addSerializationExclusionStrategy hides fields from the output but still accepts them in input, and addDeserializationExclusionStrategy does the opposite, for example to ignore a server-controlled field such as createdAt when a client sends it.

Finally, excludeFieldsWithModifiers replaces the default set of skipped modifiers, which is static and transient. Calling excludeFieldsWithModifiers(Modifier.STATIC) means transient fields are serialized again, which is occasionally needed for classes whose transient fields mean something only to Java serialization. Calling it with Modifier.PROTECTED would also skip protected fields. Note that it replaces the defaults instead of adding to them, so we list every modifier we still want skipped.

Java
Gson g1 = new GsonBuilder().excludeFieldsWithModifiers(Modifier.STATIC).create();
// transient cache is now written: {..., "cache":{}}
Gson g2 = new GsonBuilder().addDeserializationExclusionStrategy(serverOwned).create();
// a client-supplied "createdAt" is ignored on input, still written on output
Which exclusion tool to use
MechanismScopeBest for
transientone field, every toolderived or cached data
@Expose + excludeFieldsWithoutExposeAnnotationallow-list per classobjects crossing a trust boundary
ExclusionStrategyrule across all classescompany rules, such as @Internal
add(De)SerializationExclusionStrategyone directionwrite-only or read-only fields
excludeFieldsWithModifiersby modifierchanging the static/transient default

6Follow-up questions

If both @Expose and an ExclusionStrategy apply, which wins?

Exclusion is cumulative: a field is written only if no mechanism excludes it. So a field with @Expose is still skipped if a strategy says to skip it, and a field without @Expose is skipped under excludeFieldsWithoutExposeAnnotation no matter what the strategy says.

Is excluding fields the best way to protect sensitive data in an API?

For anything security-relevant, a response DTO that contains only the public fields is better than excluding fields from an entity, because the DTO cannot leak a field it does not have. Exclusion tools are best for shaping objects we already intend to expose.

Do exclusions apply to fields of nested objects?

Yes. Gson applies the same rules to every class it serializes through reflection, so an @Internal field inside a nested object is skipped too. Types handled by a custom TypeAdapter are the exception, because the adapter decides what to write.

7Conclusion

In this answer, we saw five ways to exclude fields in Gson. transient is quick but affects Java serialization and JPA as well. @Expose with excludeFieldsWithoutExposeAnnotation turns Gson into an allow-list, with per-direction flags. An ExclusionStrategy expresses rules across classes, such as a custom @Internal annotation, and can be applied to one direction only. excludeFieldsWithModifiers replaces the default skipping of static and transient fields. For data that must never leave the service, a dedicated DTO is the strongest option.

What to say in the interviewAbout 70 seconds aloud

Open with

There are a few levels. The simplest is the transient keyword, which Gson skips by default along with static fields. I use it for derived or cached data, but I am careful because transient is a language keyword: Java serialization and JPA also honour it, so on an entity it would stop the field being persisted.

Then, if they want more

The second option is an allow-list: build Gson with excludeFieldsWithoutExposeAnnotation and annotate the fields to include with @Expose, where serialize and deserialize flags control each direction, for example a password that is accepted but never written. That is the safest for objects crossing a trust boundary, since new fields are hidden by default.

Third, an ExclusionStrategy, with shouldSkipField and shouldSkipClass, expresses company-wide rules, like skipping anything with a custom @Internal annotation that has runtime retention, or never serializing a SecretKey type. setExclusionStrategies applies it both ways, while addSerializationExclusionStrategy and addDeserializationExclusionStrategy apply it in one direction. Finally, excludeFieldsWithModifiers replaces the default static and transient set, for instance to serialize transient fields again.

For truly sensitive data, though, I would rather return a DTO that does not contain the field at all.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "List the ways to exclude a field from Gson serialization and say when you would use each.": https://scrivio-interview-library.netlify.app/java/json-libraries/e87ee091c6/