How to Handle JSON Polymorphism and Inheritance with Jackson

JSON polymorphism allows one API payload to represent several related Java types. A payment request, for example, might be a card payment, bank transfer, or digital wallet transaction while sharing common fields such as an identifier and amount.

Jackson can map these payloads to an inheritance hierarchy, but it needs a reliable way to identify the concrete subtype. Without that information, deserialisation may fail with an abstract-type error or produce an object with the wrong behaviour.

This approach is useful in Spring Boot applications, REST APIs, event-driven systems, and integrations that serve customers across Sydney, Melbourne, Brisbane, and regional Australia. It is especially valuable when an API must support several business workflows without duplicating shared model code.

The safest design treats the JSON contract as a public interface. Type names, required fields, validation rules, and unknown-property behaviour should be documented and tested, particularly when Australian privacy obligations and consumer-facing data handling are involved.

Strategy JSON Example Best Use
Logical type name "kind": "card" Stable public APIs
Wrapper object "card": { ... } Explicit message contracts
Existing property "paymentType": "card" Payloads with a natural discriminator
Deduction from fields "cardNumber": "..." Legacy or uncontrolled JSON

Model Polymorphism Clearly

Begin with an abstract base class or interface containing the fields shared by every subtype. A payment model could contain amount, currency, and reference, while specialised classes add card or bank-account details.

Use a discriminator property such as kind rather than relying on class names. Class names expose implementation details, and renaming CardPayment to CreditCardPayment can break clients. A short, stable value such as card is easier to version and document.

Choose A Type Strategy

Jackson supports several polymorphic representations. The right choice depends on whether you control the producer, need backward compatibility, and want the JSON to remain easy for JavaScript or mobile clients to consume.

A consistent discriminator also helps teams working across time zones and Australian states. A Melbourne service and a Perth client can exchange the same contract without relying on local naming conventions or framework defaults.

Configure Jackson Safely

A common annotation-based model looks like this:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "kind"
)
@JsonSubTypes({
    @JsonSubTypes.Type(value = CardPayment.class, name = "card"),
    @JsonSubTypes.Type(value = BankPayment.class, name = "bank")
})
public abstract class Payment {
    private BigDecimal amount;
    private String currency;
}

The subtype can then add its own fields:

public class CardPayment extends Payment {
    private String lastFourDigits;
}

Jackson reads {"kind":"card","amount":25.00,"currency":"AUD"} and creates a CardPayment. In Spring Boot, the same ObjectMapper configuration normally applies to controller request bodies and response objects.

Handle Collections And APIs

Polymorphism becomes particularly useful for collections such as List<Payment>, where each element can have a different concrete type. The discriminator must be present on every item, or Jackson cannot select the correct class during deserialisation.

For API responses, keep the discriminator visible unless there is a strong reason to hide it. OpenAPI documentation should describe every permitted subtype, required property, and example payload. When integrating an Australian payment provider or commissioning payment integration specialists, align the external contract with the internal Java hierarchy before implementation begins.

Sensitive fields require extra care. Do not serialise full card numbers, authentication tokens, or unnecessary identity data. The Privacy Act 1988 and the Australian Privacy Principles make data minimisation and secure handling important for applications storing customer information.

Test Real Payloads

Unit tests should cover both successful subtype resolution and invalid discriminator values. Test serialisation as well as deserialisation, because an apparently correct input model can still produce an incompatible response.

Include contract tests against real examples from external systems. An Australian retailer may send prices in AUD and dates in local time, while a national service must also handle daylight-saving differences between Sydney and Brisbane. These details can expose integration faults that simple class-level tests miss.

Connect Persistence And Services

Jackson annotations belong to the API representation, not necessarily to the database model. Keeping DTOs separate from JPA entities prevents persistence concerns, lazy-loading behaviour, and internal class names from leaking into public JSON.

A service layer can convert a PaymentRequest DTO into a domain object after validation. This gives the application a clear place to enforce rules such as accepted currencies, payment limits, and Australian Consumer Law obligations for refunds or cancelled services.

For event messaging, include a schema version alongside the type discriminator when long-lived messages are involved. Consumers can then distinguish a card payment in version one from a future version with changed fields without guessing from the Java package structure.

Avoid Production Surprises

Security is a central concern when polymorphic deserialisation accepts type metadata. Avoid unrestricted default typing for untrusted input, especially configurations that allow arbitrary Java class names. Prefer explicit logical names and a known subtype list.

Use @JsonTypeName or central subtype registration when annotations would clutter domain classes. For large systems, a dedicated module can register all permitted subtypes and apply consistent naming rules across services.

Log deserialisation failures without recording complete customer payloads. This supports troubleshooting while reducing exposure of personal information. Clear error responses should identify an unsupported payment kind or missing field, but should not reveal internal class names, stack traces, or security configuration.