Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Configure a Gson instance that pretty-prints, includes nulls, uses snake_case field names, does not escape HTML characters, and formats a LocalDate as yyyy-MM-dd.

We chain the builder methods: new GsonBuilder().setPrettyPrinting().serializeNulls().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).disableHtmlEscaping().registerTypeAdapter(LocalDate.class, new LocalDateAdapter()).create(), where LocalDateAdapter is a TypeAdapter<LocalDate> that writes value.toString() and reads with LocalDate.parse. setDateFormat would not help here, because it only applies to java.util.Date, and the finished Gson should be one shared instance.

Why this question is asked

Most real projects need a Gson that differs from the defaults: readable output for logs and files, explicit nulls for a strict contract, snake_case names for an API written in another language, and real dates. Each requirement maps to one builder call, but two of them hide traps: HTML escaping, which surprises people the first time they see \u003c in their JSON, and dates, where the obvious method does nothing for java.time. Interviewers like this coding question because a correct answer shows we know the builder and its limits. In this answer, we will build the instance one setting at a time, write the LocalDate adapter, see the output, and finish with why the instance must be shared.

1A Quick Recap of GsonBuilder

new Gson() gives an instance with default settings. GsonBuilder is how we change them: each method returns the builder, so calls chain, and create() produces an immutable, thread-safe Gson with those settings. Here is the class we will serialize and what default Gson does with it.

Java
public class Booking {
private String guestName = "Ana <VIP>";
private LocalDate checkIn = LocalDate.of(2026, 11, 5);
private String roomNote = null;
}
System.out.println(new Gson().toJson(new Booking()));
// on recent JDKs: JsonIOException, Gson tries to reflect into LocalDate's private fields
// without java.time involved, it would print: {"guestName":"Ana \u003cVIP\u003e"}

Every requirement in the question fixes one problem in that line: it is on one line, the null roomNote is missing, names are camelCase, < and > are escaped, and the LocalDate either fails or comes out as its internal fields.

2The Simple Settings

Four of the five requirements are plain builder switches. setPrettyPrinting() writes indented, multi-line JSON, nice for humans and slightly larger. serializeNulls() writes fields whose value is null as "field": null instead of omitting them. setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) translates guestName into guest_name for every field, so we do not need an annotation on each one. disableHtmlEscaping() stops Gson from escaping HTML-sensitive characters.

That last one needs an explanation. By default, Gson writes characters such as <, >, &, = and the apostrophe as unicode escapes like \u003c. The reason is safety: if JSON is ever embedded directly in an HTML page, an unescaped </script> in a string could end the script block. The escaped JSON is still valid and parses back to the same string, but it is hard to read. For an API that returns application/json, the escaping is unnecessary, so disabling it is common.

3A TypeAdapter for LocalDate

Gson has no built-in support for java.time, and setDateFormat("yyyy-MM-dd") will not help, because it only configures the adapter for java.util.Date and its java.sql subclasses. So we write a small TypeAdapter. LocalDate.toString() already produces yyyy-MM-dd, the ISO-8601 date format, and LocalDate.parse reads it.

Java
final class LocalDateAdapter extends TypeAdapter<LocalDate> {
@Override public void write(JsonWriter out, LocalDate value) throws IOException {
if (value == null) { out.nullValue(); return; } // keep nulls working
out.value(value.toString()); // "2026-11-05"
}
@Override public LocalDate read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; }
return LocalDate.parse(in.nextString()); // "2026-11-05" -> 2026-11-05
}
}

Notice the null handling in both methods. Because we asked for serializeNulls(), Gson will call our adapter with null values, and a careless out.value(value.toString()) would throw NullPointerException. If we wanted a different pattern, such as dd.MM.yyyy, we would hold a DateTimeFormatter in the adapter and use format and parse with it; DateTimeFormatter is immutable and thread-safe, so one instance is enough.

4Putting the Builder Together

Now we combine everything.

Java
public final class Json {
public static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.disableHtmlEscaping()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
private Json() { }
}
System.out.println(Json.GSON.toJson(new Booking()));
// {
// "guest_name": "Ana <VIP>",
// "check_in": "2026-11-05",
// "room_note": null
// }
Booking b = Json.GSON.fromJson("{\"check_in\":\"2026-12-01\"}", Booking.class);
System.out.println(b.checkIn); // 2026-12-01
Each requirement and the call that meets it
RequirementBuilder callEffect on Booking
Pretty printingsetPrettyPrinting()indented, one field per line
Include nullsserializeNulls()"room_note": null
snake_case namessetFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES)guestName -> guest_name
No HTML escapingdisableHtmlEscaping()<VIP> instead of \u003cVIP\u003e
LocalDate as yyyy-MM-ddregisterTypeAdapter(LocalDate.class, ...)"2026-11-05"

Every requirement shows up in the output: indentation, the explicit null, snake_case names, a readable <VIP>, and the date as a plain string. Reading works with the same rules, so check_in maps back to the checkIn field and through our adapter.

5Why the Instance Must Be Shared

A Gson instance caches the type adapters it builds for each class. Creating a configured instance in every method throws that cache away, which is slower, and more importantly invites drift: sooner or later someone creates their own instance and forgets disableHtmlEscaping or the date adapter, and the same class comes out differently on two code paths. So we create one instance, as a static constant like above or as a Spring bean, and use it everywhere.

6Follow-up questions

Why not use setDateFormat("yyyy-MM-dd")?

Because it configures only Gson's built-in adapter for java.util.Date, java.sql.Date and java.sql.Timestamp. It has no effect on LocalDate, LocalDateTime or Instant, which need their own adapters.

Does pretty printing affect parsing?

No. Whitespace between tokens is ignored by every JSON parser, so pretty-printed and compact JSON parse to the same values. Pretty printing only costs bytes, so APIs often leave it off and use it only for files and logs that people read.

Is it safe to disable HTML escaping?

Yes for an API that returns application/json, which browsers do not execute as HTML. It matters only if our code places JSON text directly inside an HTML page, in which case that page should escape it at the point of embedding anyway.

7Conclusion

In this answer, we built a Gson instance with setPrettyPrinting, serializeNulls, the LOWER_CASE_WITH_UNDERSCORES naming policy and disableHtmlEscaping, and added a null-safe TypeAdapter<LocalDate> that writes toString() and reads LocalDate.parse. We saw that default HTML escaping turns characters like < into unicode escapes for safety in HTML pages, that setDateFormat applies only to java.util.Date, and that the finished instance should be created once and shared.

What to say in the interviewAbout 70 seconds aloud

Open with

I would build it with GsonBuilder and keep the result as one shared instance. setPrettyPrinting gives indented output, serializeNulls writes null fields instead of dropping them, setFieldNamingPolicy with FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES turns firstName into first_name for every field, and disableHtmlEscaping stops Gson from writing characters like the less-than sign, ampersand and equals as unicode escapes, which it does by default so the JSON is safe to embed in HTML.

Then, if they want more

For the date, I cannot use setDateFormat because that only affects java.util.Date and the java.sql types, and Gson has no built-in java.time support. So I write a TypeAdapter<LocalDate>: write checks for null and calls out.nullValue, otherwise out.value(value.toString()), which is already yyyy-MM-dd; read checks peek for JsonToken.NULL and otherwise returns LocalDate.parse(in.nextString()).

The null handling matters because with serializeNulls the adapter will see nulls. I register it with registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) and call create. Finally, I would expose the instance as a static constant or a Spring bean, because Gson is thread-safe and caches adapters, and separate instances tend to drift apart.

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 "Configure a Gson instance that pretty-prints, includes nulls, uses snake_case field...": https://scrivio-interview-library.netlify.app/java/json-libraries/27e1141f89/