Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a Gson TypeAdapter that writes a Money(BigDecimal amount, String currency) as the string "12.50 EUR" and reads it back. When would you use JsonSerializer and JsonDeserializer instead?

We extend TypeAdapter<Money>: write() calls out.value(m.amount().toPlainString() + " " + m.currency()), and read() checks in.peek() for JsonToken.NULL, then splits in.nextString() on the space and builds a Money. We register it with registerTypeAdapter(Money.class, new MoneyAdapter().nullSafe()). JsonSerializer and JsonDeserializer work on an in-memory JsonElement tree instead of the stream, so they are simpler for small changes but slower and use more memory; we pick them for convenience and TypeAdapter for performance.

Why this question is asked

Money is a good example of a type whose default JSON is wrong for the business. Gson's reflective adapter would write {"amount":12.50,"currency":"EUR"}, and a partner API may instead require the compact string "12.50 EUR". Getting this right also means getting the details right: no scientific notation for amounts, correct nulls, and a clear error for bad input. Interviewers ask this coding question to see whether we can write a correct streaming adapter and whether we understand the trade-off with Gson's older tree-based interfaces. In this answer, we will recap the two APIs, write the adapter step by step, register it, test it, and then compare it with JsonSerializer and JsonDeserializer.

1A Quick Recap of Gson's Two Customisation APIs

Gson offers two ways to take over the JSON for a type. A TypeAdapter works directly on the stream: write() receives a JsonWriter, which writes tokens to the output as we call it, and read() receives a JsonReader, which hands us the next token from the input. Nothing is built in memory beyond what we create ourselves.

JsonSerializer and JsonDeserializer are the older pair. A serializer turns our object into a JsonElement, which is Gson's tree model of JSON (JsonObject, JsonArray, JsonPrimitive, JsonNull), and Gson then writes that tree. A deserializer receives an already-parsed JsonElement and returns our object. The tree is easier to inspect and change, but it exists in memory for every value.

2Writing the TypeAdapter

Here is the type and its adapter.

Java
public record Money(BigDecimal amount, String currency) { }
final class MoneyAdapter extends TypeAdapter<Money> {
@Override
public void write(JsonWriter out, Money m) throws IOException {
if (m == null) { out.nullValue(); return; } // writes null
out.value(m.amount().toPlainString() + " " + m.currency()); // "12.50 EUR"
}
@Override
public Money read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; }
String text = in.nextString(); // "12.50 EUR"
String[] parts = text.split(" ");
if (parts.length != 2) {
throw new JsonParseException("Expected '<amount> <currency>' but was: " + text);
}
return new Money(new BigDecimal(parts[0]), parts[1]); // Money[amount=12.50, currency=EUR]
}
}

Notice toPlainString() rather than toString(). A BigDecimal created as new BigDecimal("1E+3") prints 1E+3 with toString() but 1000 with toPlainString(), and a partner parsing "1E+3 EUR" would reject it. BigDecimal also keeps its scale, so 12.50 stays 12.50 and does not become 12.5, which matters for money.

In read(), we must consume the null token with nextNull() before returning, otherwise the reader is left pointing at it and the next read fails. We also validate the shape and throw JsonParseException with the bad text, so a broken payload produces a message someone can act on, not an ArrayIndexOutOfBoundsException. new BigDecimal(parts[0]) will itself throw NumberFormatException for an invalid amount, which we could wrap the same way.

3Registering the Adapter

We register the adapter on the shared builder.

Java
Gson gson = new GsonBuilder()
.registerTypeAdapter(Money.class, new MoneyAdapter().nullSafe())
.create();
record Invoice(String id, Money total, Money discount) { }
String json = gson.toJson(new Invoice("A1", new Money(new BigDecimal("12.50"), "EUR"), null));
System.out.println(json); // {"id":"A1","total":"12.50 EUR"}
Invoice back = gson.fromJson(json, Invoice.class);
System.out.println(back.total().amount()); // 12.50

nullSafe() wraps the adapter in one that writes null for a null value and returns null when it reads a JSON null, without calling our code at all. Since it already handles nulls, the checks inside our adapter become a second line of defense; many teams write the adapter without them and always register it with nullSafe(). Either style works, as long as nulls are handled somewhere. Notice also that the null discount does not appear in the output, because the default Gson omits null fields before the adapter is even consulted.

4What Happens on Each Call

It helps to see the flow when Gson writes an Invoice. The reflective adapter for Invoice walks its fields, and when it reaches a Money field it hands the stream to our adapter for that one value.

Step throughGson writing an Invoice with a Money field
GsonInvoice adapterMoneyAdapterJsonWriter
write(invoice)
name("id"), value("A1")
write(total)
value("12.50 EUR")
done
done

6 messages in order. Play them, or step through them one at a time.

Because our adapter writes a single string token, Money stays a primitive value in the JSON, which is exactly what the partner expects.

5When to Use JsonSerializer and JsonDeserializer Instead

The same mapping with the tree API is a little shorter, because the tree has already been parsed for us and we work with ready-made values.

Java
JsonSerializer<Money> ser = (m, type, ctx) ->
new JsonPrimitive(m.amount().toPlainString() + " " + m.currency());
JsonDeserializer<Money> de = (json, type, ctx) -> {
String[] p = json.getAsString().split(" ");
return new Money(new BigDecimal(p[0]), p[1]);
};
Gson gson = new GsonBuilder()
.registerTypeAdapter(Money.class, ser)
.registerTypeAdapter(Money.class, de)
.create();

Gson handles nulls for this pair itself, which is convenient. The JsonDeserializationContext, ctx, also lets us delegate parts of a larger object back to Gson, which makes the tree API pleasant for objects where we only want to change one field or inspect a discriminator.

The cost is that every value goes through an intermediate JsonElement. For one Money that is negligible, but in a payload with a million amounts it means a million extra objects to allocate and collect. So the rule of thumb is: a TypeAdapter for types that appear often or in large payloads, and for anything on a hot path; the tree API for small, rarely used customisations where clarity matters more than speed.

6Follow-up questions

Why not use Gson's default and just send amount and currency as two fields?

If we control both sides, two fields are often better, because the amount stays a JSON number or string and does not need parsing. The adapter is for contracts that already use the compact form, or for keeping JSON identical to an existing API.

Should the amount be a JSON number instead of part of a string?

Many money APIs send amounts as strings precisely to avoid binary floating-point problems in clients, since JavaScript parses JSON numbers into doubles. Combining amount and currency into one string is one variant of that idea; the important rule is never to let the amount pass through a double.

Can a TypeAdapter for Money be reused for a List<Money>?

Yes. Gson's collection adapter looks up the element adapter for each element, so once Money is registered, List<Money>, Map<String, Money> and Money fields in any class all use it automatically.

7Conclusion

In this answer, we wrote a streaming TypeAdapter<Money> whose write() emits a single string built with toPlainString() and the currency, and whose read() handles a JSON null, splits the string and validates its shape. We registered it with nullSafe(), which handles nulls around it, and saw how Gson hands it one value at a time. JsonSerializer and JsonDeserializer achieve the same with a JsonElement tree, which is simpler to write but costs memory and speed, so TypeAdapter is the choice for frequent types and large payloads.

What to say in the interviewAbout 80 seconds aloud

Open with

I would extend TypeAdapter<Money>. In write, if the value is null I call out.nullValue, otherwise out.value with the amount's toPlainString plus a space plus the currency. I use toPlainString so a BigDecimal never comes out in scientific notation, and BigDecimal keeps the scale, so 12.50 stays 12.50.

Then, if they want more

In read, I check in.peek for JsonToken.NULL, consume it with nextNull and return null; otherwise I read nextString, split on the space, validate that there are exactly two parts, and build the Money with new BigDecimal and the currency, throwing a JsonParseException with the bad text if the shape is wrong.

I register it on the shared GsonBuilder with registerTypeAdapter(Money.class, new MoneyAdapter().nullSafe()); nullSafe handles nulls around the adapter, so the inner checks are just a second line of defense. As for JsonSerializer and JsonDeserializer, they work on a JsonElement tree instead of the stream.

They are a bit simpler, Gson handles nulls for them, and the context can delegate parts back to Gson, so they are fine for small, rare customisations. But every value goes through an intermediate tree, so for frequent types or large payloads I prefer TypeAdapter, which is streaming and faster.

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 "Write a Gson TypeAdapter that writes a Money(BigDecimal amount, String currency) as the...": https://scrivio-interview-library.netlify.app/java/json-libraries/7c9689b70e/