Polymorphic Double-Label Serialisation
Written by Mohamed Moanes
At SumUp, scalability goes beyond transaction volumes — it’s also about building flexible, resilient client-side architectures. Within the SumUp Interaction Platform, this philosophy drives our real-time chat infrastructure. We rely on a fully event-driven architecture to process a continuous stream of diverse support actions over persistent socket connections.
Managing the highly polymorphic JSON payloads required to coordinate these fast-moving, multi-sender chat interactions on the client is exactly what led us to design a custom solution: PolymorphicDoubleLabelJsonAdapterFactory.
TL;DR
Moshi’s built-in PolymorphicJsonAdapterFactory picks a Kotlin subtype based on one JSON field (e.g. "type"). That's enough most of the time—but real-world APIs like our socket events often need two fields to identify the concrete subtype (e.g. "event" + "sender").
PolymorphicDoubleLabelJsonAdapterFactory maps subtypes using a (primaryLabel, secondaryLabel) pair. It completely preserves the intuitive design of the original Moshi API, retaining the exact same fluent withSubtype(...) chaining, fallback defaults, and automatic .nullSafe() handling.
1. The problem Moshi’s built-in factory doesn’t solve
Moshi ships with a powerful utility called PolymorphicJsonAdapterFactory. A typical use case looks like this:
Given the payload {“event”:”started”, “timestamp”:1718533000}, Moshi reads the event key, looks up "started", and dispatches parsing to the SessionStarted data class. Clean and declarative.
Where it falls short
Real-world APIs or event streams often reuse the same broad type for multiple variants, using a second field to differentiate between them:
In our dynamic support interaction, both the client and the server emit a generic "message" event structure. However, the exact data layout changes completely based on who the sender is
Trying to force standard Moshi to handle these multi-layered payloads forces you into some frustrating architectural trade-offs:
The monolithic data class: Collapsing every single variant into one massive model where almost every field is nullable, completely breaking compile-time type safety.
The custom wrapper layer: Introducing an intermediate middleman that intercepts the raw JSON, inspects the keys, and manually re-dispatches the payload after an initial parsing pass.
The custom adapter: Writing a
JsonAdapterfrom scratch, forcing you to manually re-implement low-level logic like JSON flattening, peeking, skipping, and fallback routines.
All of those options leak parsing concerns into your domain. PolymorphicDoubleLabelJsonAdapterFactory keeps the same declarative style, but lets the pair of fields decide the subtype.
2. The core concept
When configuring the factory, you declare:
A base type (sealed/abstract class or interface),
A primary label key (always required, e.g.
"event"),An optional secondary label key (e.g.
"sender"),A list of
(primaryLabel, secondaryLabel?)-> subtype mappings,Optionally, a default value is returned when the backend sends a label the app doesn’t know yet.
The deserialisation pipeline
At write time (toJson), it uses the concrete subtype's adapter and flattens its fields into the parent JSON object. The configuration keys remain clean siblings of the payload, preventing nested structures.
3. Public API at a glance
The factory's public structural shape mirrors Square’s native utilities perfectly. You can grab the complete internal wiring directly from this GitHub Gist:
Fluent builder API
Note: Each
with*call returns a new instance of the factory (an immutable builder pattern), ensuring compound initialization chains are fully thread-safe.
4. Three real-world scenarios
Scenario A: Single-type key (parity with native Moshi)
If you only pass a primary key, it behaves like Moshi’s standard polymorphic adapter, with the bonus of an optional default.
When to reach for this over Moshi’s own factory? when you want the graceful fallback behaviour (forward-compatibility with new backend variants without an app update).
Scenario B: Two types of keys (the core feature)
The backend routes multiple message variants through a single event field, differentiating payload contracts by a secondary sender field.
Why this helps: Every single variant remains a decoupled, strongly typed Kotlin data class. You don’t end up with a unified, confusing model full of optional properties.
Scenario C: Many-to-one value aliasing
Sometimes, multiple upstream API labels map to the exact same client domain model (e.g., both "delivered" and "seen" mean Acknowledgement).
Both entries correctly parse into the same class. Note: Serialisation (toJson) is inherently asymmetric here—it will pick the first registered label for that subtype. This pattern is ideal for read-only consumption like Server-Sent Events (SSE).
5. Direct comparison
6. When not to use it
Implicit type keys:
If your API infers types by field presence (e.g., “if
card_tokenexists, it's a card"), polymorphic factories won't work. Use a standard customJsonAdapter.Semantic overlap: If the same key shares conflicting meanings or types across variants, flattening will cause issues. Nest the payload inside a data object and parse it with a dedicated adapter.
Deep structural tiers: If you need three or more selective identifiers, a factory isn’t the right tool. Push back on the backend contract architecture or handle it via a manual domain-specific parsing layer.
Symmetric round-tripping requirements: If you map multiple labels to the same subtype,
toJsoncan't guess which of the original labels you wanted during serialisation. Keep the mapping 1-to-1 or split the model into distinct subtypes.
7. Operational best practices
Order for readability: Order doesn’t matter logically for different combinations, but registering the most specific mappings first makes the call site easier to read and maintain.
Always define a fallback: If you don’t control the upstream API, always append
.withDefaultValue().Streams, Webhooks, and socket channels routinely deploy new variants; a missing mapping shouldn't crash your entire serialisation pipeline.
Use sealed objects as sentinels: Make your default value a concrete object within your hierarchy (e.g.,
DynamicInteraction.Unknown). This forces your UI layer to explicitly handle or ignore fallback states via compile-time exhaustivewhen checks.Watch your
toJsonpath: Encoding an unregistered subtype throws anIllegalArgumentException. If you do round-trip an unknown sentinel object back to the server, register an adapter for it too, or filter it out before serialising.
Don’t add the adapter twice: Like all Moshi factories, registering the exact same factory for the same base type twice leads to undefined ordering errors.
8. End-to-end execution sample
9. Summary
Standard polymorphic parsing solves textbook setups, but real-world enterprise architectures are rarely that tidy. Instead of creating convoluted, multi-stage mapping layers, extending Moshi with a composite parser lets you preserve declarative codebases, enforce compile-time model separation, and protect your client applications from structural changes on the backend.
Feel free to download, inspect, or submit improvements directly to the implementation on GitHub Gist.
Inside SumUp's AI hackathon: From idea to prototype in 48 hours
See how 85 SumUppers turned everyday challenges into working AI prototypes in just 48 hours at our Berlin AI Hackathon. No coding required.
Evaluating an LLM application for generating free-text narratives in financial crime
Explore the effectiveness of an LLM application in generating financial crime narratives and how this technology enhances compliance and risk assessment.
The power of flow-based SLOs
Introduces a flow-based Service Level Objective framework that measures reliability across complete user journeys instead of individual services, providing a more user-centric view of system health.