Quick revision
The short answer
We annotate the base type with @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") so Jackson reads the type field to choose a class, and list the allowed subtypes with @JsonSubTypes, for example @JsonSubTypes.Type(value = Card.class, name = "card"). Each subtype declares only its own fields. Reading a List<PaymentMethod> then gives Card and Bank objects, and an unknown type value fails with an InvalidTypeIdException unless we configure a default type or relax that feature.
What to remember
In this answer, we deserialized a list of payment methods by putting @JsonTypeInfo(use = Id.NAME, property = "type") and @JsonSubTypes on a sealed PaymentMethod interface, with Card and Bank as records holding only their own fields. Reading with a TypeReference produced the right subclass for each element, and a sealed switch let the compiler check we handle every kind. Unknown or missing type values fail with InvalidTypeIdException, which becomes a 400 in Spring MVC, unless we add a defaultImpl or disable FAIL_ON_INVALID_SUBTYPE, and the same annotations write the type field back on output.
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 annotate the base type with @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") so Jackson reads the type field to choose a class, and list the allowed subtypes with @JsonSubTypes, for example @JsonSubTypes.Type(value = Card.class, name = "card"). Each subtype declares only its own fields. Reading a List<PaymentMethod> then gives Card and Bank objects, and an unknown type value fails with an InvalidTypeIdException unless we configure a default type or relax that feature.
Why this question is asked
Many APIs send lists of things that share a purpose but not a shape: payment methods, notifications, shapes in a drawing. In JSON they arrive as objects with a discriminator field, here type, and our code wants proper Java classes rather than a map of maybe-present fields. Interviewers ask this coding question because it shows whether we know Jackson's polymorphic type handling, and whether we use the safe variant of it. In this answer, we will recap how Jackson picks a class, write the model with a sealed interface and records, read a mixed list, look at what happens with unknown or missing types, and check how the same model is written back.
1A Quick Recap: How Jackson Chooses the Class
When Jackson reads JSON into a declared type, it normally creates exactly that type. If the declared type is an interface such as PaymentMethod, it has nothing to create and fails. Polymorphic type handling solves this: @JsonTypeInfo tells Jackson that the JSON carries a type id and where to find it, and @JsonSubTypes gives the list of allowed classes with the name each one uses. While reading, Jackson finds the type field, looks the name up in that list, and deserializes the rest of the object as the matching class.
Id.NAME means the type id is a logical name we choose, such as card. That is important for safety and for evolution: the client never names a Java class, only one of the names we listed.
2Writing the Model
A sealed interface is a natural fit, because the set of payment methods is closed and the compiler then knows every case. The subtypes are records with their own fields; they do not declare the type field, because Jackson handles it.
Notice that the annotations sit on the base type only. Each record declares exactly the fields its kind of payment has, so there is no Card with a null iban or a Bank with an expiry date. The include style defaults to PROPERTY, meaning the type id is an ordinary field inside the object, which is what our clients send.
3Reading a Mixed List
To read a JSON array into a list of the base type, Jackson must know the element type, which Java erases at runtime. A TypeReference keeps it. In a Spring controller, a @RequestBody List<PaymentMethod> parameter works directly, because Spring passes the full generic type to Jackson.
- Read the type field"card"
- Is "card" in @JsonSubTypes?YesUse Card.classNoInvalidTypeIdException (or defaultImpl)
- Deserialize the other fields as Cardholder, last4, expiry
- Add Card to the listthen the next element
4 steps in order. Play them, or step through them one at a time.
Notice the switch has no default branch. Because PaymentMethod is sealed, the compiler checks that every subtype is handled, so adding a third method later makes every such switch fail to compile until it is updated. The type field and the class hierarchy now say the same thing in two places, JSON and Java, and the compiler keeps the Java side honest.
4Unknown and Missing Type Values
If a client sends a type we did not list, say {"type":"paypal"}, Jackson fails with an InvalidTypeIdException that says it could not resolve type id paypal as a subtype of PaymentMethod and lists the known ids. If the type field is missing, it fails with a similar exception about a missing type id. In Spring MVC both become an HttpMessageNotReadableException and a 400, which is the right answer for a request: the client sent something we do not support.
Notice that the right choice depends on who sends the data. For a request to our own API, failing with a 400 is usually best, because silently dropping a payment method would be a bug. For data we read from elsewhere, such as events from another service that may add types before we do, a fallback type that we log and skip lets older readers keep working. A fallback class should usually ignore unknown properties, since it will receive fields from types it knows nothing about.
5Writing the Model Back
The same annotations work for writing. Jackson adds the type field with the subtype's name to each object, so the output matches the input format and a round trip gives the same JSON.
Notice one subtle point with generic collections. Writing a List<PaymentMethod> directly can lose the element type because of erasure; with the annotation on the interface, Jackson still finds it on each element's class here, but when in doubt we use mapper.writerFor(new TypeReference<List<PaymentMethod>>() {}) so the type information is written reliably.
6Follow-up questions
Can the subtype also have a field called type?
It can, if we use include = JsonTypeInfo.As.EXISTING_PROPERTY, which tells Jackson the type id is a real property of the class. Then the class must write it itself, for example as a constant accessor, and we should add visible = true if we also want the value passed to the object when reading. For most models it is simpler to let Jackson own the field.
Does Jackson discover the subtypes of a sealed interface automatically?
Not in the Jackson 2 versions most services use; we list them with @JsonSubTypes, or register them with mapper.registerSubtypes(new NamedType(Card.class, "card")). Check the release notes of your Jackson version, since support for sealed types has been discussed and may differ in Jackson 3.
Why not use Id.CLASS and avoid the list?
Because then the client chooses which Java class Jackson creates, which has been the source of many deserialization vulnerabilities, and it also ties the JSON to our package names. Id.NAME with a fixed list keeps control on our side and lets us rename classes freely.
7Conclusion
In this answer, we deserialized a list of payment methods by putting @JsonTypeInfo(use = Id.NAME, property = "type") and @JsonSubTypes on a sealed PaymentMethod interface, with Card and Bank as records holding only their own fields. Reading with a TypeReference produced the right subclass for each element, and a sealed switch let the compiler check we handle every kind. Unknown or missing type values fail with InvalidTypeIdException, which becomes a 400 in Spring MVC, unless we add a defaultImpl or disable FAIL_ON_INVALID_SUBTYPE, and the same annotations write the type field back on output.
Open with
I'd model it as a sealed interface PaymentMethod with two records, Card and Bank, each holding only its own fields. On the interface I put @JsonTypeInfo with use = Id.NAME and property = "type", which tells Jackson to read the type field and treat its value as a logical name, and @JsonSubTypes listing Card with name card and Bank with name bank.
Then, if they want more
When I read the array, with a TypeReference of List of PaymentMethod, or as a @RequestBody List in a controller, Jackson looks at each element's type, finds the class in that list and deserializes the remaining fields into it. When writing, it adds the type field back, so the format round-trips.
Because the interface is sealed, a switch over the payment methods is checked by the compiler for completeness. For unknown values like paypal, Jackson throws InvalidTypeIdException, and a missing type field fails similarly; in Spring MVC that's a 400, which I think is right for requests to our own API.
If the data comes from another system that might add types first, I'd add a defaultImpl fallback class that I log and skip, or disable FAIL_ON_INVALID_SUBTYPE so unknown entries become null. I'd always use Id.NAME rather than Id.CLASS, so the client can only pick from the names I listed, never an arbitrary class.
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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
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 "Deserialize a list of payment methods where each JSON object has a type field (card or...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/56d64e71d9/