I have the following field (map of maps):
private final Map<Class<? extends Something>, Map<String, ? super Something>> somethings;
I need to serialize the Class<?>
keys using Class::getSimpleName
instead of Class::toString
, hence I have created my custom key serializer:
public final class ClassSerializer extends JsonSerializer<Class<?>> {
@Override
public void serialize(Class<?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeFieldName(value.getSimpleName());
}
}
... and I'm using it on the field with keyUsing
:
@JsonSerialize(keyUsing = ClassSerializer.class)
@JsonProperty("somethings")
private final Map<Class<? extends Something>, Map<String, ? super Something>> somethings;
The problem is that this key serializer is used also when serializing the internal maps which contain a simple String
as key, so causing a JsonMappingException
with message class java.lang.String cannot be cast to class java.lang.Class
.
I understand what happens but I don't know how to tell Jackson to use such serializer only for the keys of type Class
, and not for all the keys that it may potentially find inside.
Any idea?