1

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?

javadev
  • 688
  • 2
  • 6
  • 17
Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89
  • seems like a duplicate of https://stackoverflow.com/questions/46836372/json-custom-key-serialization-of-nested-maps. The solution there is quite obvious, maybe you are looking for something "cleaner" – Pedro Oct 26 '21 at 11:46
  • @dariosicily that's what I did but I was looking for something cleaner – Matteo NNZ Oct 26 '21 at 12:03
  • @Pedro that's what I did but I was looking for something cleaner – Matteo NNZ Oct 26 '21 at 12:03
  • I think the second option in the accepted answer of that question is as clean as it gets. I was looking at Jackson's source and there seems to be no way around it. – Pedro Oct 26 '21 at 12:10
  • It may be worth opening an issue for it on Jackson's Github. Maybe request adding a keyUsingNested boolean to the JsonSerializer annotation. – Pedro Oct 26 '21 at 12:13
  • If `Class` keys are just in the main map and not inside you could do `ClassSerializer extends JsonSerializer` and check `value instanceof Class` inside the method. – dariosicily Oct 26 '21 at 13:17
  • @dariosicily yes I did that, I was just looking for a cleaner way to do it. – Matteo NNZ Oct 26 '21 at 13:34
  • I ran out of ideas, if some viewer had one I would like to know it too. – dariosicily Oct 26 '21 at 13:45

0 Answers0