Quick revision
The short answer
We write a TypeAdapterFactory that, for the PaymentMethod base type, reads each object as a small tree, looks at its type field, and hands the object to the adapter for the matching concrete class, obtained with gson.getDelegateAdapter so we avoid infinite recursion and keep any other registered adapters. Type names map to an allow-list of classes, never to a class name taken from the input, and unknown types either fail with a clear error or map to an explicit Unknown variant. Gson's RuntimeTypeAdapterFactory does this too, but it lives in the extras, not the main artifact, so a copied version must be reviewed.
What to remember
In this answer, we saw that Gson cannot choose a subclass from a field value, so we wrote a TypeAdapterFactory for PaymentMethod that reads each object as a tree, looks up its type in an allow-list, and delegates to the concrete class's adapter obtained with getDelegateAdapter, which prevents recursion and keeps other adapters working. Writing adds the type name back. We never load classes named by the input, we review any copied RuntimeTypeAdapterFactory, and we decide deliberately whether unknown types fail clearly or map to an Unknown variant.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We write a TypeAdapterFactory that, for the PaymentMethod base type, reads each object as a small tree, looks at its type field, and hands the object to the adapter for the matching concrete class, obtained with gson.getDelegateAdapter so we avoid infinite recursion and keep any other registered adapters. Type names map to an allow-list of classes, never to a class name taken from the input, and unknown types either fail with a clear error or map to an explicit Unknown variant. Gson's RuntimeTypeAdapterFactory does this too, but it lives in the extras, not the main artifact, so a copied version must be reviewed.
Why this question is asked
Polymorphic data is everywhere: payment methods, notification channels, shapes, events. The JSON carries a discriminator, a field such as type that says which kind of object this is, and the Java side has a base type with several implementations. Jackson has @JsonTypeInfo and @JsonSubTypes for this, but Gson has no annotation, so we must write the logic ourselves. Interviewers ask this design question because a naive solution either recurses forever, loses other adapters, or, worst of all, creates arbitrary classes named by the attacker. In this answer, we will see why plain Gson fails, design the factory step by step, write it, look at the safety rules, and decide what to do with unknown types.
1Why Plain Gson Cannot Do It
Here is the model and the input.
Gson only knows the declared type, PaymentMethod. It cannot create an interface, and even for an abstract class it would have no idea which subclass the type field refers to. Gson does not look at field values to choose classes. We need to teach it.
2The Design: Read the Discriminator, Then Delegate
The plan for reading is: parse the object into a JsonObject tree so we can look at it without consuming the stream twice, read its type value, look that value up in a fixed map of allowed names to classes, and let the normal adapter for that class turn the tree into an object. Writing is the reverse: find the name for the object's class, let the class's adapter produce a tree, add the type property, and write it out.
The subtle part is how we get the normal adapter for each concrete class. A TypeAdapterFactory is something Gson asks, for each type it meets, "can you build an adapter for this?". Inside a factory, gson.getDelegateAdapter(this, type) asks Gson for the adapter that would have been used if our factory did not exist. This avoids recursion when our factory would also match the type, and it keeps every other registered adapter in play, for example a custom adapter for a Money field inside Card.
- Parse the object as a JsonObjectusing Gson's
JsonElementadapter - Is there a type field?YesRead its valueNoFail: missing type
- Is the value in the allow-list?YesGet the delegate adapter for that classNoFail, or map to Unknown
- Delegate converts the tree
fromJsonTree(obj) - Return Card or BankAccount
5 steps in order. Play them, or step through them one at a time.
3Writing the TypeAdapterFactory
Here is a compact version of the factory.
Notice that the factory returns null for every type that is not PaymentMethod, which tells Gson to keep looking. The type property left in the tree is harmless when the delegate reads it, because Gson ignores unknown properties. And because the delegate adapters are looked up once per Gson instance, not per value, the cost per object is just the small tree.
4Safety: Never Load Classes From the Input
A tempting shortcut is to put the class name itself in the JSON, "type":"com.acme.Card", and call Class.forName on it. That turns the JSON into an instruction to instantiate any class on the classpath, which is the root of many deserialization vulnerabilities: an attacker names a class whose constructor or setters do something dangerous, and our parser runs it. The allow-list map avoids this completely. The JSON can only choose between the names we listed, and each name points to a class we wrote. Short names like card and bank also keep Java package names out of the public contract, so we can refactor freely.
Gson's source repository contains RuntimeTypeAdapterFactory in its extras module, which implements this same pattern with registerSubtype calls. It is not part of the main gson artifact, so teams usually copy the file into their code. That is acceptable, but the copy then belongs to us: we should review it, pin the version we copied, and check how it handles unknown labels and nulls.
5Deciding What Unknown Types Mean
Sooner or later a producer adds "type":"wallet" before the consumer knows about it. There are two honest choices. Rejecting with a clear error, as above, is right when processing an unknown method would be wrong, for example when charging a customer. Mapping to an explicit variant, a record Unknown(String type, JsonObject raw) implements PaymentMethod, is right when the consumer can safely skip or display it, such as a list of saved methods in a settings page. What we must not do is silently drop the element or fall back to a default type. Whichever we choose, a test with an unknown type, a missing type and a null element pins the behaviour down.
6Follow-up questions
Why not use a JsonDeserializer instead of a factory?
A JsonDeserializer works too: read the type from the JsonElement and call context.deserialize(json, Card.class). It is simpler for reading only, but writing needs a matching JsonSerializer, and if the serializer calls context.serialize(value) with the base type it recurses. The factory with getDelegateAdapter solves both directions cleanly and stays streaming at the outer level.
What exactly happens if we call gson.getAdapter(Card.class) instead of getDelegateAdapter?
In this factory it would work, because we only match PaymentMethod itself. But if the factory matched every subtype of PaymentMethod, getAdapter(Card.class) would call our factory again and recurse until a stack overflow. getDelegateAdapter skips our factory, so it is the safe habit.
Does sealed help here?
A sealed interface tells the compiler and readers exactly which implementations exist, so the allow-list can be checked against it in a test, and a switch over PaymentMethod can be exhaustive. Gson does not use the sealed information itself.
7Conclusion
In this answer, we saw that Gson cannot choose a subclass from a field value, so we wrote a TypeAdapterFactory for PaymentMethod that reads each object as a tree, looks up its type in an allow-list, and delegates to the concrete class's adapter obtained with getDelegateAdapter, which prevents recursion and keeps other adapters working. Writing adds the type name back. We never load classes named by the input, we review any copied RuntimeTypeAdapterFactory, and we decide deliberately whether unknown types fail clearly or map to an Unknown variant.
Open with
Gson only knows the declared type, so for a list of PaymentMethod it cannot pick Card or BankAccount from the type field. I would write a TypeAdapterFactory that only answers for PaymentMethod.
Then, if they want more
For reading, it parses each object into a JsonObject with Gson's JsonElement adapter, reads the type value, looks it up in a fixed map from names like card and bank to classes, and lets the adapter for that class convert the tree.
For writing, it finds the name for the object's class, converts the object to a tree with that class's adapter, adds the type property and writes it.
The key detail is getting those per-class adapters with gson.getDelegateAdapter(this, type), which asks Gson for the adapter it would use without my factory, so there is no recursion and any other registered adapters, like one for Money inside Card, still apply.
For safety, the type names map to an allow-list, never to a class name from the JSON, because loading classes named by input is a classic deserialization vulnerability. Gson's extras contain RuntimeTypeAdapterFactory, which does this, but it is not in the main jar, so if we copy it we review and own it.
Finally, I would test unknown and missing types, and either reject them with a clear error or map them to an explicit Unknown variant.
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 "You need polymorphic deserialization in Gson: a JSON array of payment methods where each...": https://scrivio-interview-library.netlify.app/java/json-libraries/ae05ea2d30/