Scrivio Interview library
ScenarioIntermediate5 min read · updated 12 November 2026

Each team in your service creates its own Gson with different builder settings, and the same Order class is serialized with different field names and null handling depending on the code path. How do you fix this?

We replace all the ad hoc instances with one configured Gson, created in a shared factory or as a Spring bean and injected everywhere. We document its settings, naming policy, nulls, number policy, strictness and registered adapters, lock the output of key types with tests against approved JSON samples, and ban new Gson() in production code with a static analysis rule such as an ArchUnit test, so the drift cannot return.

Why this question is asked

This situation grows naturally. One developer needs snake_case names and builds a Gson with a naming policy; another needs nulls in a log message and builds one with serializeNulls; a third just writes new Gson(). Each choice is reasonable alone, but together they mean the same Order class leaves the service in three shapes, and clients see data that depends on which code path produced it. Interviewers ask this scenario to see whether we fix the root cause, which is that configuration is spread across the code, and whether we can make the fix stick. In this answer, we will see how the drift shows up, centralise the configuration, document each setting and why it matters, protect the format with tests, and enforce the rule in the build.

1How the Drift Shows Up

Here is the problem in miniature. Three code paths, three instances, one class.

Java
// OrderController
String a = new Gson().toJson(order);
// {"orderId":7,"total":12.5}
// OrderEventPublisher
String b = new GsonBuilder().serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create().toJson(order);
// {"order_id":7,"total":12.5,"coupon":null}
// AuditLogger
String c = new GsonBuilder().setPrettyPrinting().create().toJson(order);
// pretty-printed, camelCase, no coupon key

A consumer that reads both the REST response and the event has to handle orderId and order_id, and a missing coupon versus a null one. Nothing is technically broken, which is why this survives code review: each instance is valid on its own.

2One Configured Instance

The fix is to make the configuration a single, named thing. In a Spring application, that is a bean; in plain Java, a small factory class with a static instance. Gson is immutable and thread-safe after create(), so one instance can serve every thread.

Java
@Configuration
class JsonConfig {
@Bean
Gson gson() {
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.serializeNulls()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.setStrictness(Strictness.STRICT) // Gson 2.11+; older: setLenient()
.registerTypeAdapter(Instant.class, new InstantAdapter().nullSafe())
.registerTypeAdapter(Money.class, new MoneyAdapter().nullSafe())
.create();
}
}
@Component
class OrderEventPublisher {
private final Gson gson;
OrderEventPublisher(Gson gson) { this.gson = gson; } // injected, never built here
}
Step throughWhere JSON configuration lives after the fix
  1. Controllers, publishers, loggersinject Gson; never construct it
  2. Shared Gson bean or factorythe only GsonBuilder in production code
  3. Registered adaptersInstant, Money and other shared types
  4. Approved JSON samples and testslock the output of key types

4 layers, from the top down. Step through them one at a time.

Now there is exactly one place that decides how an Order looks. A shared library can expose the same factory for services that are not built on Spring. Pretty printing is deliberately not part of the shared instance: if the audit log wants indentation, it can call gson.newBuilder().setPrettyPrinting().create() once, which copies every other setting, so only the whitespace differs.

3Document Each Setting and Why

Writing down the settings matters because each one is a decision about the contract, and future developers need to know it was deliberate. The naming policy decides the keys clients see. The null setting decides whether a missing value is absent or null. The number policy decides what happens when JSON numbers are read into Object or Map fields: by default Gson turns them all into Double, so an id of 7 comes back as 7.0, while ToNumberPolicy.LONG_OR_DOUBLE keeps integers as Long.

Strictness decides how forgiving parsing is. A lenient parser accepts things that are not valid JSON, such as unquoted names, single quotes or comments, which can hide broken producers. Gson 2.11 added setStrictness with LEGACY_STRICT, LENIENT and STRICT, replacing setLenient; the default behaviour has differed between methods and versions, so check your version and choose one value deliberately rather than inheriting it. Finally, the list of registered adapters documents every type whose JSON form we chose by hand.

4Lock the Output With Approved Samples

Configuration can still change by accident, during a Gson upgrade or a well-meant edit. So we write tests that serialize the key types and compare the result with approved JSON files kept in the repository.

Java
@Test
void orderJsonMatchesApprovedSample() {
Order order = Fixtures.order(7, new Money("12.50", "EUR"), null);
String json = gson.toJson(order);
JSONAssert.assertEquals(read("approved/order.json"), json, JSONCompareMode.STRICT);
// {"order_id":7,"total":"12.50 EUR","coupon":null} or the build fails
}

When a format change is intended, the developer updates the approved file in the same pull request, so the change is visible in review instead of being discovered by a client.

5Make the Old Pattern Impossible

Without enforcement, someone will write new Gson() again next month. An ArchUnit test, a library that checks architecture rules in a unit test, can forbid it everywhere except the configuration class.

Java
@ArchTest
static final ArchRule noAdHocGson = noClasses()
.that().doNotHaveSimpleName("JsonConfig")
.should().callConstructor(Gson.class)
.orShould().callConstructor(GsonBuilder.class)
.because("use the shared Gson bean so every path writes the same JSON");
// fails the build and names the class and line that creates its own instance

An Error Prone custom check or a Semgrep rule achieves the same in projects that prefer compile-time tooling. The point is that the rule is checked by the build, not by memory.

6Follow-up questions

What about the clients that already depend on the different shapes?

Before switching every path to the shared instance, we compare the old outputs with the new one. Where an external client reads one of the old shapes, we keep that path's format through a versioned endpoint or event schema, announce the change, and move the client deliberately.

Why not just switch the service to Jackson while we are at it?

It may be the right long-term step, but it is a bigger change with different defaults. Centralising Gson first gives us one configuration and approved samples, which are exactly what we need to migrate to Jackson safely later.

Should tests use the same Gson bean?

Yes. Tests that build their own Gson can pass while production behaves differently. Injecting the real bean, or calling the same factory, means the tests check the configuration clients actually see.

7Conclusion

In this answer, we saw that per-team Gson instances make the same class serialize differently on each code path. We fix it with one configured Gson in a shared factory or Spring bean, document its naming, null, number and strictness settings and its adapters, protect the output with approved-sample tests, and forbid new Gson() outside the configuration with an ArchUnit or Error Prone rule. Variants such as pretty printing are derived with newBuilder() from the shared instance, so they differ only where intended.

What to say in the interviewAbout 80 seconds aloud

Open with

The root cause is that JSON configuration is spread across the code, so I would make it one thing. I create a single configured Gson, as a Spring bean or in a shared factory, and inject it everywhere; Gson is immutable and thread-safe, so one instance is fine.

Then, if they want more

If one path needs a variant, like pretty printing for an audit log, it derives it with newBuilder from the shared instance so every other setting stays the same.

Then I document the settings, because each is a contract decision: the field naming policy, whether nulls are serialized, the number policy, since by default numbers read into Object or Map become Double and ToNumberPolicy.LONG_OR_DOUBLE keeps integers, the strictness, which in Gson 2.11 is setStrictness and replaces setLenient, and the list of registered adapters.

Next I add tests that serialize key types like Order and compare them with approved JSON files, so any change shows up in review. Finally, I add an ArchUnit rule that fails the build when any class other than the configuration calls the Gson or GsonBuilder constructor.

Before switching paths I would also check whether external clients rely on any of the old shapes, and move them through a versioned change if so.

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 "Each team in your service creates its own Gson with different builder settings, and the...": https://scrivio-interview-library.netlify.app/java/json-libraries/dd1aace81a/