Creating custom Jackson serializers and deserializers
Jackson’s ObjectMapper already converts most Java values correctly, but APIs often need a stricter or different contract. A custom serializer can emit an amount as a decimal string instead of a JSON number; a custom deserializer can validate that string before it reaches business logic.
That matters in Australian projects, where totals commonly use AUD and cents, partner feeds may expect DD/MM/yyyy, and invoices can carry standard 10% GST. Sydney and Melbourne change between AEST and AEDT, while Brisbane remains on AEST, so timestamps need an explicit offset or named zone.
Choose the right Jackson extension point
Start with Jackson’s built-in mappings and a DTO. If only one field needs different treatment, use @JsonSerialize(using = ...) and @JsonDeserialize(using = ...) on that property. This keeps the exception visible and avoids changing every BigDecimal in the application.
Reserve a global SimpleModule for a wire format shared by a dedicated type, such as a Money value object. A mapper-wide rule for BigDecimal is risky because the same Java type may represent a price, tax component, quantity, or internal ratio.
Build a focused value serializer
A serializer should transform one value and leave whole-request validation to the service layer. For monetary values, write a fixed-scale decimal string with BigDecimal, never double, and let a JsonMappingException report invalid input.
public final class AudAmountSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator out,
SerializerProvider provider) throws IOException {
out.writeString(value.setScale(2, RoundingMode.UNNECESSARY).toPlainString());
}
}
public final class AudAmountDeserializer extends JsonDeserializer<BigDecimal> {
@Override
public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
if (!p.hasToken(JsonToken.VALUE_STRING)) {
throw ctxt.reportInputMismatch(
BigDecimal.class, "AUD amount must be a string");
}
String raw = p.getText().trim();
try {
return new BigDecimal(raw).setScale(2, RoundingMode.UNNECESSARY);
} catch (ArithmeticException | NumberFormatException ex) {
throw JsonMappingException.from(p, "Invalid AUD amount", ex);
}
}
}
The deserializer rejects excess precision rather than silently rounding a payable amount. In production, also cap input length and numeric exponent before constructing BigDecimal; otherwise a hostile exponent can create an expensive object. Null handling belongs in an explicit annotation such as @JsonInclude, or in a documented null-value method.
Handle incoming JSON safely
Parsing policy should be as deliberate as output. Configure FAIL_ON_UNKNOWN_PROPERTIES deliberately and define how nulls, empty strings, and unexpected token types behave. Use mapping exceptions to report the offending path, and avoid locale-sensitive parsing because the host locale may differ from an Australian client’s settings.
| Jackson mechanism | Best fit | Main consideration |
|---|---|---|
| Field annotations | One exceptional property | Repetition across DTOs |
| Custom serializer | A reusable output format | Must define null and error behaviour |
| Custom deserializer | Strict parsing or conversion | Must reject ambiguous input |
SimpleModule |
A shared value type | Can affect the whole mapper |
For dates, prefer ISO 8601, such as 2026-01-05T14:30:00+11:00, for machine interfaces. Accept DD/MM/yyyy only when a partner contract requires it, and validate it as a date rather than inferring the day from a locale. Likewise, keep time-zone conversion in java.time; a Brisbane server must not silently supply Sydney time.
Register modules without coupling
Register a module as a Spring bean when Jackson should own the rule centrally. Keep the module small, name its scope clearly, and avoid registering a new ObjectMapper inside a controller. Spring Boot can discover a Module bean, while tests can build the same configuration without starting the full web application.
Prefer annotations for deliberate one-off differences and modules for consistent domain rules. This separation matters when an API evolves: DTOs can change independently from JPA entities, and each custom mapper can have a narrow unit test. If an amount is absent, document whether the field is omitted, sent as null, or rejected.
Keep persistence concerns outside JSON
A common failure is serialising lazy JPA proxies, which triggers database queries and exposes persistence details. Map a stable DTO instead, and copy only fields required by the contract. If an application also uses Hibernate's second-level cache, remember that ORM caching and JSON mapping solve different problems; cache tuning cannot make an unsafe entity graph safe.
Australian fintech and e-commerce integrations commonly need a supplier ABN, an AUD total, and GST information in the same payload. An invoice DTO can represent the ABN as a string and preserve leading zeroes, while keeping entity relationships and lazy collections out of Jackson’s path.
Production patterns and verification
Keep custom mapping narrow, observable, and easy to remove when the contract changes. Two practical checklists help separate implementation choices from verification work:
- Emit monetary values as decimal strings with two fractional digits; never use binary floating point.
- Define null, empty-string, unknown-property, and extra-precision behaviour explicitly.
- Bound input length and exponent before constructing
BigDecimal. - Use explicit offsets for timestamps and keep date parsing locale-independent.
Pair unit tests with contract tests using payloads exchanged by Australian partners:
- Cover AUD cents, standard GST amounts, and an ABN with a leading zero.
- Test valid
DD/MM/yyyyinput, invalid dates, and AEDT-to-AEST transitions. - Keep monetary and non-monetary
BigDecimalfields separate in test fixtures. - Snapshot the final JSON and verify content type, nulls, and unknown fields.
A focused custom mapping rule gives the client a stable contract, gives the service a controlled boundary, and leaves Jackson’s default behaviour intact everywhere else.