Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a custom serializer that writes a Money(amount, currency) object as "12.50 EUR" and register it.

We extend StdSerializer<Money> and in serialize() call gen.writeString(amount + " " + currency), using amount.toPlainString() so the number never appears in scientific notation. We register it either with @JsonSerialize(using = MoneySerializer.class) on the Money type or in a SimpleModule, which Spring Boot 3 picks up automatically as a Module bean or through a @JsonComponent class (Boot 4 has a Jackson 3 equivalent). A matching StdDeserializer reads "12.50 EUR" back, so the format works in both directions.

Why this question is asked

Money is the type where default JSON goes wrong most often. Jackson would write a Money record as an object with a number, and numbers in JSON lose scale (12.50 becomes 12.5) and can lose precision in JavaScript clients. A single string such as 12.50 EUR keeps the amount exact and the currency attached. Interviewers ask this coding question because it covers the serializer API, the ways to register it, how Spring Boot finds it, and the often forgotten other half: reading the value back. In this answer, we will write the serializer, register it three ways, write the deserializer with proper error handling, and test the round trip. The code uses Jackson 2 names, as in Spring Boot 3, and we will note the Jackson 3 changes.

1A Quick Recap of How Jackson Writes a Value

When Jackson writes an object, it looks up a serializer for the object's class: a small object whose serialize method receives the value and a JsonGenerator, the low-level writer that emits JSON tokens. For a record or a bean, Jackson builds a serializer that writes each property as a field. If we provide our own serializer for Money, Jackson uses ours instead, and whatever we write with the generator becomes the JSON for that value.

Without a custom serializer, our type comes out like this, which is what we want to change.

Java
public record Money(BigDecimal amount, String currency) {}
mapper.writeValueAsString(new Money(new BigDecimal("12.50"), "EUR"));
// {"amount":12.50,"currency":"EUR"} default: an object with a JSON number

2Writing the Serializer

StdSerializer is Jackson's convenient base class for serializers. We pass the handled type to its constructor and override serialize. The body is one call to writeString, but two details matter for money.

Java
public class MoneySerializer extends StdSerializer<Money> {
public MoneySerializer() { super(Money.class); }
@Override
public void serialize(Money value, JsonGenerator gen, SerializerProvider provider) throws IOException {
int digits = Currency.getInstance(value.currency()).getDefaultFractionDigits(); // EUR: 2, JPY: 0
BigDecimal scaled = value.amount().setScale(digits, RoundingMode.UNNECESSARY); // fails if 12.505
gen.writeString(scaled.toPlainString() + " " + value.currency());
}
}
// new Money(new BigDecimal("12.5"), "EUR") -> "12.50 EUR"
// new Money(new BigDecimal("1E+3"), "EUR") -> "1000.00 EUR" (toString() would give "1E+3")
// new Money(new BigDecimal("500"), "JPY") -> "500 JPY"

Notice toPlainString(). BigDecimal.toString() uses scientific notation for some values, so an amount created as 1E+3 would be written as 1E+3 EUR, which no client expects. Notice also the scale: we format the amount with the currency's usual number of decimals, so 12.5 is written as 12.50. RoundingMode.UNNECESSARY makes the serializer throw if the amount has more decimals than the currency allows, which is better than silently rounding someone's money; if the domain allows such amounts, we would choose a rounding mode deliberately instead.

3Registering the Serializer

There are three common ways, and they differ in who decides. With @JsonSerialize on the Money type, the type itself says how it is written, which is simple and works with any mapper, but couples the domain class to Jackson. With a SimpleModule, the mapper decides, and the domain class stays clean. In Spring Boot 3, a Module bean is registered with Boot's mapper automatically, and so is a class annotated with @JsonComponent that holds serializers.

Java
// 1. On the type
@JsonSerialize(using = MoneySerializer.class)
@JsonDeserialize(using = MoneyDeserializer.class)
public record Money(BigDecimal amount, String currency) {}
// 2. A module as a bean (Spring Boot registers every Module bean)
@Bean
Module moneyModule() {
return new SimpleModule("money")
.addSerializer(Money.class, new MoneySerializer())
.addDeserializer(Money.class, new MoneyDeserializer());
}
// 3. @JsonComponent (Spring Boot 3)
@JsonComponent
class MoneyJson {
static class Serializer extends MoneySerializer {}
static class Deserializer extends MoneyDeserializer {}
}

Notice that only the first option works outside Spring, for example in a plain new ObjectMapper() in a test, because the annotation travels with the class. In Spring Boot 4 with Jackson 3, Module beans become JacksonModule beans and @JsonComponent has a Jackson 3 counterpart; check the Boot 4 documentation for its exact name.

4Writing the Matching Deserializer

A serializer without a deserializer makes the format one-way: we can send 12.50 EUR, but a client cannot send it back in a request. The deserializer reads the string, splits it and validates both parts. When the input is wrong, we report it through the DeserializationContext so Jackson produces a proper InvalidFormatException, which Spring MVC turns into a 400 rather than a 500.

Java
public class MoneyDeserializer extends StdDeserializer<Money> {
public MoneyDeserializer() { super(Money.class); }
@Override
public Money deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String text = p.getValueAsString(); // "12.50 EUR"
String[] parts = text == null ? new String[0] : text.trim().split(" ");
try {
if (parts.length == 2) {
Currency.getInstance(parts[1]); // rejects "EURO"
return new Money(new BigDecimal(parts[0]), parts[1]);
}
} catch (IllegalArgumentException e) { // NumberFormatException is one too
// fall through to the error below
}
return (Money) ctxt.handleWeirdStringValue(Money.class, text,
"expected '<amount> <ISO currency>', for example '12.50 EUR'");
}
}
// "12.50 EUR" -> Money[amount=12.50, currency=EUR]
// "12,50 EUR" -> InvalidFormatException (400 in Spring MVC)
// "12.50" -> InvalidFormatException
// 12.5 (number) -> getValueAsString() returns "12.5", one part -> InvalidFormatException

Notice that handleWeirdStringValue throws by default; it returns a value only if a registered problem handler decides to recover, which is why the method has a return type. Using it instead of throwing our own exception keeps Jackson's error path, including the location of the bad value in the JSON, and lets the application's error handler treat it like any other malformed field.

5Testing the Round Trip

The test that matters is that what we write we can read back unchanged, plus the edge cases we decided on.

Java
@Test
void moneyRoundTrip() throws Exception {
ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule()
.addSerializer(Money.class, new MoneySerializer())
.addDeserializer(Money.class, new MoneyDeserializer()));
String json = mapper.writeValueAsString(new Order(1, new Money(new BigDecimal("12.5"), "EUR")));
assertThat(json).isEqualTo("{\"id\":1,\"total\":\"12.50 EUR\"}");
assertThat(mapper.readValue(json, Order.class).total())
.isEqualTo(new Money(new BigDecimal("12.50"), "EUR")); // scale 2 after the round trip
assertThatThrownBy(() -> mapper.readValue("{\"id\":1,\"total\":\"12,50 EUR\"}", Order.class))
.isInstanceOf(InvalidFormatException.class);
}

Notice the comparison after the round trip uses 12.50, not 12.5. BigDecimal.equals compares scale too, so new BigDecimal("12.5") and new BigDecimal("12.50") are not equal; the record's equals inherits that. That is one more reason to fix the scale in the serializer: the value that comes back is always in the same form.

6Follow-up questions

What changes in Jackson 3?

The structure stays the same, but the names change: serializers extend StdSerializer in the tools.jackson packages, the serialize method receives a SerializationContext instead of a SerializerProvider, and methods no longer declare IOException because Jackson 3 exceptions are unchecked. SimpleModule still exists. Check the exact signatures against the Jackson version in use.

Why not write money as a JSON number?

JSON numbers have no scale, so 12.50 and 12.5 are the same number, and many JavaScript clients parse them into binary floating point, where amounts such as 0.1 cannot be represented exactly. A string keeps exactly what we sent. Some APIs prefer an object with a string amount and a currency field, which is easier to extend; a single string is compact and readable, and either works as long as it is consistent.

When would I use a serializer instead of @JsonValue?

@JsonValue is enough when the JSON is simply the result of one method, such as toString(). A serializer is better when the output needs logic, here the currency-dependent scale, or when we cannot or do not want to annotate the class.

7Conclusion

In this answer, we wrote a MoneySerializer that extends StdSerializer<Money> and writes "12.50 EUR" with gen.writeString, using toPlainString() and the currency's default number of decimals so the output is always exact and consistent. We registered it with @JsonSerialize on the type, in a SimpleModule bean, or with @JsonComponent in Spring Boot 3, with Jackson 3 equivalents in Boot 4. We added a MoneyDeserializer that parses the same format and reports bad input through handleWeirdStringValue so it becomes a 400, and we tested the round trip, including the scale.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd write a MoneySerializer that extends StdSerializer of Money, pass Money.class to the super constructor, and in serialize call gen.writeString with the amount, a space and the currency.

Then, if they want more

Two details matter for money. I use toPlainString on the BigDecimal, because toString can produce scientific notation like 1E+3. And I set the scale to the currency's default fraction digits, so 12.5 is written as 12.50 EUR and JPY has no decimals; with RoundingMode.UNNECESSARY it fails rather than silently rounding.

To register it, I can put @JsonSerialize(using = MoneySerializer.class) on the type, which works with any mapper but couples the type to Jackson, or add it to a SimpleModule.

In Spring Boot 3 a Module bean is registered automatically with Boot's mapper, and so is a @JsonComponent class; in Boot 4 with Jackson 3 the types are renamed, like SerializationContext and JacksonModule, so I'd check the equivalent there.

Then I always write the matching deserializer, a StdDeserializer that reads the string, splits it, validates the number and the ISO currency, and on bad input calls handleWeirdStringValue so Jackson throws InvalidFormatException, which becomes a 400. Finally a round-trip test, including the scale, because BigDecimal equality depends on it.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3, Spring Boot 4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 custom serializer that writes a Money(amount, currency) object as "12.50 EUR"...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/09b17f0cd9/