1

I have a class that looks like this:

@JsonDeserialize(builder=ContainerBuilder.class)
class Container {
     @JsonSerializer(using=MySerializer.class)
     @JsonDeserializer(using=MyDeserializer.class)
     ThirdPartyMap<MyKey, MyValue> map;
}

I need a custom serializer, because the keys in my map have structure, and Jackson by default creates a field with key.toString() as the field name.

I would like to make my deserializer generic, and not hard-code MyKey and MyValue as the types of the map. The class file stores the generic types of the field, so I would expect to be able to get that information. However, I have not been able to find it.

I did find Custom Jackson Deserializer Getting Access to Current Field Class which recommended using JsonParser.getCurrentValue() to (I think) get an instance of the return value and use reflection to find the field. However, since the class I am deserializing is final and made with a builder, getCurrentValue return null.

It also looks like deserializeWithType might be relevant, but I cannot figure out how to have that method called.

Edit: Type erasure does not completely erase generics at runtime. If I have a Map<String, Integer>, then by looking at the object, erasure prevents me from learning the generic parameters.

However, if I have a class like interface Data { Collection<String> getList() }, the generic information on the return type is part of the class. Indeed, it must be in the class file, as otherwise, I could put the class in a jar file and use it like this: Collection<Integer> c = data.getList(); and the compiler would not know to issue a compilation error.

Jackson must be reading the class information to know the type of the field, so it should (at least in principle) also be able to get the generic parameters on the type. Whether it does and does so in a way that is accessible to a custom deserializer is a separate question, and the underlying question here.

Troy Daniels
  • 3,270
  • 2
  • 25
  • 57
  • May you please elaborate a bit more?. In my understanding Generics are of use only at compile time, to enforce the use of a concrete class. At runtime (when you are deserializing JSON) Java does "type erasure" so it doesn't matter if you specify it or not. am I missing something here? – Manuel Vera Silvestre Apr 02 '18 at 15:17

0 Answers0