Serializing a Map<K, V>
field uses declared type for key serialization rather than key instance type
#4736
Labels
Map<K, V>
field uses declared type for key serialization rather than key instance type
#4736
Search before asking
Describe the bug
When serializing a field of type
Map<K, V>
, Jackson will inspect the declaredK
type for serialization annotations, rather than the individual entries key's instance type. This creates issues whereK
is a supertype and the map holds subtypes ofK
(K'
) that do specify serialization annotations.Values are serialized as expected and the instance type is used for annotation introspection.
Version Information
2.18.0
Reproduction
Expected behavior
In the reproducer above, the first
println
prints{"values":["foo",123]}
, the secondprintln
prints{"values":{"StringValue[value=bar]":456}}
, using the defaulttoString()
for the key. The thirdprintln
is included to display that the issue is when serializing a map field, not a map value directly as that third prints{"baz":789}
which is the kind of serialization behavior I'd expect for the second case as well.Enabling the
@JsonKey
in the interface's method makes it behave how I'd expect, and the secondprintln
now prints{"values":{"bar":456}}
. The annotation's presence when disabled doesn't play a role, as it doesn't behave any differently when it isn't there (as expected).Additional context
The most relevant issue I could find is #3119 given the inheritance setting, but explicitly specifying
@JsonSerialize(keyUsing = ...)
behaves correctly so I ruled that out, but they might be related in a way I can't see.The text was updated successfully, but these errors were encountered: